### Get Bucket Info (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving information about an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get bucket info info = api.get_bucket_info('your_bucket_name') print(f'Bucket name: {info.name}') print(f'Bucket creation date: {info.create_date}') ``` -------------------------------- ### Get Bucket Lifecycle (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving the lifecycle configuration of an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get lifecycle configuration lifecycle_config = api.get_bucket_lifecycle('your_bucket_name') print('Bucket lifecycle configuration:') for rule in lifecycle_config['LifecycleRules']: print(f' Rule ID: {rule["ID"]}') print(f' Status: {rule["Status"]}') if 'Expiration' in rule: print(f' Expiration Days: {rule["Expiration"]["Days"]}') if 'Transition' in rule: print(f' Transition Days: {rule["Transition"]["Days"]}, Storage Class: {rule["Transition"]["StorageClass"]}') ``` -------------------------------- ### Install alibabacloud_credentials SDK Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Install the necessary SDK for managing Alibaba Cloud credentials. ```bash pip install alibabacloud_credentials ``` -------------------------------- ### Get Bucket Inventory (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving the inventory configuration of an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get inventory configuration inventory_config = api.get_bucket_inventory('your_bucket_name', 'inventory-all-objects') print('Bucket inventory configuration:') print(inventory_config) ``` -------------------------------- ### Get Bucket Referer (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving the referer configuration of an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get referer configuration referer_config = api.get_bucket_referer('your_bucket_name') print(f'Allow empty referer: {referer_config["AllowEmpty"]}') print('Referer list:') for referer in referer_config['RefererList']: print(f' - {referer}') ``` -------------------------------- ### Get Bucket Tags (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving tags of an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get bucket tags tags = api.get_bucket_tags('your_bucket_name') print('Bucket tags:') for key, value in tags.items(): print(f' {key}: {value}') ``` -------------------------------- ### Get Bucket Logging (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving the access logging configuration of an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get logging configuration logging_config = api.get_bucket_logging('your_bucket_name') print('Bucket logging configuration:') print(logging_config) ``` -------------------------------- ### Create Bucket (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for creating an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Create a bucket api.put_bucket('your_bucket_name') print('Bucket created successfully.') ``` -------------------------------- ### PutBucket API Call Example Source: https://help.aliyun.com/zh/oss/developer-reference/api-reference This example demonstrates how to construct and send a request to create a bucket using the PutBucket API. It includes the necessary HTTP headers, the request body in XML format, and the expected success response. ```APIDOC ## PUT / ### Description Creates a new storage bucket. ### Method PUT ### Endpoint / ### Parameters #### Request Body - **StorageClass** (string) - Required - Specifies the storage class for the bucket. - **DataRedundancyType** (string) - Required - Specifies the data redundancy type for the bucket. ### Request Example ``` PUT / HTTP/1.1 Host: oss-example.oss-cn-hangzhou.aliyuncs.com Date: Thu, 17 Apr 2025 03:15:40 GMT x-oss-acl: private Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e Standard LRS ``` ### Response #### Success Response (200) - **Location** (string) - The location of the created bucket. #### Response Example ``` HTTP/1.1 200 OK x-oss-request-id: 534B371674E88A4D8906**** Date: Fri, 24 Feb 2017 03:15:40 GMT Content-Length: 0 Connection: keep-alive Server: AliyunOSS Location: /oss-example ``` ### Error Handling - **4xx/5xx Status Codes**: Indicate request failure. The response body will be in XML format containing specific error codes (`Code`) and messages (`Message`). ``` -------------------------------- ### List Buckets (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for listing all OSS buckets using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # List buckets buckets = api.list_buckets() for bucket in buckets: print(bucket.name) ``` -------------------------------- ### Install OSS Python SDK V2 Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Use pip to install the OSS Python SDK V2 package. It is recommended to use the latest version for compatibility with code examples. ```bash pip install alibabacloud-oss-v2 ``` -------------------------------- ### Simple Download (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for downloading a file from OSS using simple download with the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Download file response = api.get_object('your_bucket_name', 'remote_object_name.txt') with open('local_downloaded_file.txt', 'wb') as f: f.write(response.read()) print('File downloaded successfully.') ``` -------------------------------- ### Successful Bucket Creation Response Example Source: https://help.aliyun.com/zh/oss/developer-reference/api-reference This example shows a successful HTTP response (200 OK) after creating a storage bucket. A successful response typically has a Content-Length of 0 and may include a Location header indicating the created resource. ```http HTTP/1.1 200 OK x-oss-request-id: 534B371674E88A4D8906**** Date: Fri, 24 Feb 2017 03:15:40 GMT Content-Length: 0 Connection: keep-alive Server: AliyunOSS Location: /oss-example ``` -------------------------------- ### Simple Upload (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for uploading a file to OSS using simple upload with the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Upload file with open('local_file.txt', 'rb') as f: api.put_object('your_bucket_name', 'remote_object_name.txt', f) print('File uploaded successfully.') ``` -------------------------------- ### Configure OSS Client with Dedicated Domain Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version This example demonstrates how to configure the OSS client to use a dedicated domain. This is typically used for enterprise scenarios where a custom domain is required. Replace '' and the example endpoint with your specific values. ```python import alibabacloud_oss_v2 as oss def main(): # 从环境变量中加载凭证信息,用于身份验证 credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() # 加载SDK的默认配置,并设置凭证提供者 cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # 填写Bucket所在地域 cfg.region = '' # 请填写您的专有域。例如:https://service.corp.example.com cfg.endpoint = 'https://service.corp.example.com' # 使用配置好的信息创建OSS客户端 client = oss.Client(cfg) # 使用创建好的client执行后续操作... # 当此脚本被直接运行时,调用main函数 if __name__ == "__main__": main() # 脚本入口,当文件被直接运行时调用main函数 ``` -------------------------------- ### Create Bucket API Request Example Source: https://help.aliyun.com/zh/oss/developer-reference/api-reference This example demonstrates the structure of an HTTP request to create a storage bucket using the PutBucket API. Ensure you have your AccessKey and the correct Endpoint for your region. The Authorization header must be correctly formatted according to Signature Version 4. ```http PUT / HTTP/1.1 Host: oss-example.oss-cn-hangzhou.aliyuncs.com Date: Thu, 17 Apr 2025 03:15:40 GMT x-oss-acl: private Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e Standard LRS ``` -------------------------------- ### Put Bucket Tags (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for setting tags for an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Set bucket tags tags = {'key1': 'value1', 'key2': 'value2'} api.put_bucket_tags('your_bucket_name', tags) print('Bucket tags set successfully.') ``` -------------------------------- ### Get Bucket Storage Capacity (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving the storage capacity of an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get bucket stat stat = api.get_bucket_stat('your_bucket_name') print(f'Bucket size: {stat.size} bytes') print(f'Bucket object count: {stat.object_count}') ``` -------------------------------- ### Get Bucket Encryption (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving the server-side encryption configuration of an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get encryption configuration encryption_config = api.get_bucket_encryption('your_bucket_name') print('Bucket encryption configuration:') print(encryption_config) ``` -------------------------------- ### Custom Domain Operations (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Examples for managing custom domain bindings for an OSS bucket using the Python SDK V2. This includes creating, getting, updating, listing, and deleting CNAME tokens and bindings. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Create a CNAME token token = api.create_cname_token('your_bucket_name') print(f'CNAME token created: {token}') # Get CNAME token (if needed) # token = api.get_cname_token('your_bucket_name') # Bind custom domain api.put_cname('your_bucket_name', 'your.custom.domain.com') print('Custom domain bound.') # List custom domains cnames = api.list_cname('your_bucket_name') print('Bound custom domains:') for cname in cnames: print(f'- {cname}') # Delete custom domain binding # api.delete_cname('your_bucket_name', 'your.custom.domain.com') # print('Custom domain unbound.') ``` -------------------------------- ### Describe Regions (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for querying OSS endpoint information (regions) using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Describe regions regions = api.describe_regions() for region in regions: print(f'Region ID: {region.region_id}, Region Name: {region.region_name}') ``` -------------------------------- ### Put Object Tagging (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for setting tags for an OSS object using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Set object tags tags = {'purpose': 'backup', 'version': '1.0'} api.put_object_tagging('your_bucket_name', 'your_object_name.txt', tags) print('Object tags set successfully.') ``` -------------------------------- ### Put Symlink (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for creating a symbolic link to an object in OSS using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Create symlink api.put_symlink('your_bucket_name', 'symlink_name', 'target_object_name') print('Symlink created successfully.') ``` -------------------------------- ### Range Download (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for downloading a specific range of bytes from an OSS object using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Download a range of bytes headers = {'Range': 'bytes=0-99'} response = api.get_object('your_bucket_name', 'remote_object_name.txt', headers=headers) with open('local_downloaded_range.txt', 'wb') as f: f.write(response.read()) print('File range downloaded successfully.') ``` -------------------------------- ### Complete Bucket WORM (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for completing a WORM retention configuration for an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Complete WORM retention api.complete_bucket_worm('your_bucket_name') print('Bucket WORM retention completed.') ``` -------------------------------- ### Get Object Tagging (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving tags of an OSS object using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get object tags tags = api.get_object_tagging('your_bucket_name', 'your_object_name.txt') print('Object tags:') for key, value in tags.items(): print(f' {key}: {value}') ``` -------------------------------- ### Get Symlink (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving the target of a symbolic link in OSS using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get symlink target target = api.get_symlink('your_bucket_name', 'symlink_name') print(f'Symlink target: {target}') ``` -------------------------------- ### Initialize Asynchronous OSS Client Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Initialize an asynchronous OSS client using `alibabacloud-oss-v2.aio`. Requires `aiohttp` to be installed. Ensure to close the client in a `finally` block. ```python import asyncio import alibabacloud_oss_v2 as oss import alibabacloud_oss_v2.aio as oss_aio async def main(): """ Python SDK V2 异步客户端初始化配置说明: 1. 签名版本:Python SDK V2 默认使用 V4 签名,提供更高的安全性 2. Region配置:初始化 AsyncClient 时,必须指定阿里云 Region ID 作为请求地域标识 3. Endpoint配置: - 可通过Endpoint参数自定义服务请求的访问域名 - 当不指定 Endpoint 时,将根据 Region 自动构造公网访问域名 4. 协议配置: - SDK 默认使用 HTTPS 协议构造访问域名 - 如需使用 HTTP 协议,在指定域名时明确指定 5. 异步特性: - 导入异步模块:import alibabacloud_oss_v2.aio as oss_aio - 创建异步客户端:oss_aio.AsyncClient(cfg) - 所有操作需要使用 await 关键字 - 需要在 finally 块中调用 await client.close() 关闭连接 - 需要安装 aiohttp 依赖:pip install aiohttp """ # 从环境变量中加载凭证信息,用于身份验证 credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() # 加载SDK的默认配置,并设置凭证提供者 cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # 方式一:只填写Region(推荐) # 必须指定Region ID,SDK会根据Region自动构造HTTPS访问域名 cfg.region = '' # # 方式二:同时填写Region和Endpoint # # 必须指定Region ID # cfg.region = '' # # 填写Bucket所在地域对应的外网Endpoint # cfg.endpoint = '' # 使用配置好的信息创建OSS异步客户端 client = oss_aio.AsyncClient(cfg) try: # 定义要上传的字符串内容 text_string = "Hello, OSS!" data = text_string.encode('utf-8') # 将字符串编码为UTF-8字节串 # 执行异步上传对象的请求,指定存储空间名称、对象名称和数据内容 # 注意:使用 await 关键字等待异步操作完成 result = await client.put_object( oss.PutObjectRequest( bucket="Your Bucket Name", key="Your Object Key", body=data, ) ) # 输出请求的结果状态码、请求ID、ETag,用于检查请求是否成功 print(f'status code: {result.status_code}\n' f'request id: {result.request_id}\n' f'etag: {result.etag}' ) except Exception as e: print(f'上传失败: {e}') finally: # 关闭异步客户端连接(重要:避免资源泄漏) await client.close() # 当此脚本被直接运行时,调用main函数 if __name__ == "__main__": # 使用 asyncio.run() 运行异步主函数 asyncio.run(main()) ``` -------------------------------- ### Initialize OSS Client with Environment Variables (Python) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Initialize an OSS client in Python by loading credentials from environment variables. Ensure the region is correctly set. ```python import alibabacloud_oss_v2 as oss def main(): # 从环境变量中加载访问OSS所需的认证信息,用于身份验证 credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() # 加载SDK的默认配置,并设置凭证提供者 cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # 填写Bucket所在地域 cfg.region = '' # 使用配置好的信息创建OSS客户端 client = oss.Client(cfg) # 使用创建好的client执行后续操作... # 当此脚本被直接运行时,调用main函数 if __name__ == "__main__": main() # 脚本入口,当文件被直接运行时调用main函数 ``` -------------------------------- ### Get Bucket Location (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving the region of an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get bucket location location = api.get_bucket_location('your_bucket_name') print(f'Bucket location: {location}') ``` -------------------------------- ### Configure OSS Client with Government Cloud Endpoint Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version This example demonstrates how to configure the OSS client for Alibaba Cloud's government cloud environments. It specifies the region and endpoint for a government cloud deployment. Replace placeholders with your specific government cloud region and endpoint. ```python import alibabacloud_oss_v2 as oss def main(): # 从环境变量中加载凭证信息,用于身份验证 credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() # 加载SDK的默认配置,并设置凭证提供者 cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # 填写Region和Endpoint # 填写Bucket所在地域。以华北2 阿里政务云1为例,Region填写为cn-north-2-gov-1 cfg.region = 'cn-north-2-gov-1' # 填写Bucket所在地域对应的内网Endpoint。以华北2 阿里政务云1为例,Endpoint填写为'https://oss-cn-north-2-gov-1-internal.aliyuncs.com', # 如需指定为http协议,请在指定域名时填写为'http://oss-cn-north-2-gov-1-internal.aliyuncs.com' cfg.endpoint = 'https://oss-cn-north-2-gov-1-internal.aliyuncs.com' # 使用配置好的信息创建OSS客户端 client = oss.Client(cfg) # 使用创建好的client执行后续操作... # 当此脚本被直接运行时,调用main函数 if __name__ == "__main__": main() # 脚本入口,当文件被直接运行时调用main函数 ``` -------------------------------- ### Get Bucket CORS (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving the CORS configuration of an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get CORS configuration cors_config = api.get_bucket_cors('your_bucket_name') print('Bucket CORS configuration:') for rule in cors_config['CORSRules']: print(f' Allowed Origin: {rule["AllowedOrigin"]}') print(f' Allowed Method: {rule["AllowedMethod"]}') ``` -------------------------------- ### Client-Side Encryption Get Object (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for downloading an object that was encrypted using client-side encryption with the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Download and decrypt object # Requires a KMS client or similar for decryption key management. # Refer to the GitHub example file for a complete implementation. print('Refer to encryption_get_object.py for full implementation.') ``` -------------------------------- ### Initiate Bucket WORM (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for initiating a Write-Once-Read-Many (WORM) retention policy for an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Initiate WORM retention retention_date = '2025-12-31T00:00:00Z' api.initiate_bucket_worm('your_bucket_name', retention_date) print('Bucket WORM retention initiated.') ``` -------------------------------- ### Get Object ACL (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving the Access Control List (ACL) of an OSS object using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get object ACL acl = api.get_object_acl('your_bucket_name', 'your_object_name.txt') print(f'Object ACL: {acl}') ``` -------------------------------- ### Get Bucket ACL (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving the Access Control List (ACL) of an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get bucket ACL acl = api.get_bucket_acl('your_bucket_name') print(f'Bucket ACL: {acl}') ``` -------------------------------- ### Get Bucket Request Payment (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving the request payment mode of an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get request payment mode payment_mode = api.get_bucket_request_payment('your_bucket_name') print(f'Bucket request payment mode: {payment_mode}') ``` -------------------------------- ### Get Bucket Resource Group (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving the resource group associated with an OSS bucket using the Python SDK V2. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get bucket resource group resource_group_id = api.get_bucket_resource_group('your_bucket_name') print(f'Bucket resource group ID: {resource_group_id}') ``` -------------------------------- ### Download using Presigned URL (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for downloading a file from OSS using a presigned URL with the Python SDK V2. This allows temporary download access without sharing credentials. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Generate presigned URL for download presigned_url = api.presigner_get_object('your_bucket_name', 'remote_object_name.txt', expires_in=3600) print(f'Presigned URL for download: {presigned_url}') # Then use this URL with a tool like curl or a web browser to download the file. ``` -------------------------------- ### Get Object Meta (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for retrieving object metadata using the Python SDK V2. This is similar to head_object but might provide more details depending on the SDK version. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Get object meta meta = api.get_object_meta('your_bucket_name', 'your_object_name.txt') print(f'ETag: {meta.get("etag")}') print(f'Content-Length: {meta.get("content-length")}') ``` -------------------------------- ### Put Bucket Access Monitor (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for configuring access monitoring for an OSS bucket using the Python SDK V2. This helps track access patterns and detect suspicious activity. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Set access monitor configuration access_monitor_config = { 'Status': 'Enabled', 'Project': 'your_project_id' } api.put_bucket_access_monitor('your_bucket_name', access_monitor_config) print('Bucket access monitor configured successfully.') ``` -------------------------------- ### AppendObject Response Example Source: https://help.aliyun.com/zh/oss/developer-reference/appendobject This is a standard response example for the AppendObject operation. Key headers include ETag, Content-Length, x-oss-hash-crc64ecma, and x-oss-next-append-position. ```HTTP HTTP/1.1 200 OK Date: Wed, 08 Jul 2015 06:57:01 GMT ETag: "0F7230CAA4BE94CCBDC99C550000****" Connection: keep-alive Content-Length: 0 Server: AliyunOSS x-oss-hash-crc64ecma: 14741617095266562575 x-oss-next-append-position: 1717 x-oss-request-id: 559CC9BDC755F95A6448**** ``` -------------------------------- ### HTTP Response Example for AbortMultipartUpload Source: https://help.aliyun.com/zh/oss/developer-reference/abortmultipartupload This example demonstrates a successful HTTP response when aborting a multipart upload. A 204 status code indicates success with no content. ```http HTTP/1.1 204 Server: AliyunOSS Content-length: 0 Connection: keep-alive x-oss-request-id: 059a22ba-6ba9-daed-5f3a-e48027df**** Date: Wed, 22 Feb 2012 08:32:21 GMT x-oss-server-time: 86 ``` -------------------------------- ### Initialize Synchronous OSS Client Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Initialize a synchronous OSS client by loading credentials from environment variables and configuring the region. This client is used for standard object operations. ```python import alibabacloud_oss_v2 as oss def main(): """ Python SDK V2 客户端初始化配置说明: 1. 签名版本:Python SDK V2 默认使用 V4 签名,提供更高的安全性 2. Region配置:初始化 Client 时,必须指定阿里云 Region ID 作为请求地域标识 3. Endpoint配置: - 可通过Endpoint参数自定义服务请求的访问域名 - 当不指定 Endpoint 时,将根据 Region 自动构造公网访问域名 4. 协议配置: - SDK 默认使用 HTTPS 协议构造访问域名 - 如需使用 HTTP 协议,在指定域名时明确指定 """ # 从环境变量中加载凭证信息,用于身份验证 credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() # 加载SDK的默认配置,并设置凭证提供者 cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # 方式一:只填写Region(推荐) # 必须指定Region ID,SDK会根据Region自动构造HTTPS访问域名 cfg.region = '' # # 方式二:同时填写Region和Endpoint # # 必须指定Region ID # cfg.region = '' # # 填写Bucket所在地域对应的外网Endpoint # cfg.endpoint = '' # 使用配置好的信息创建OSS客户端 client = oss.Client(cfg) # 定义要上传的字符串内容 text_string = "Hello, OSS!" data = text_string.encode('utf-8') # 将字符串编码为UTF-8字节串 # 执行上传对象的请求,指定存储空间名称、对象名称和数据内容 result = client.put_object(oss.PutObjectRequest( bucket="Your Bucket Name", key="Your Object Key", body=data, )) # 输出请求的结果状态码、请求ID、ETag,用于检查请求是否成功 print(f'status code: {result.status_code}\n' f'request id: {result.request_id}\n' f'etag: {result.etag}' ) # 当此脚本被直接运行时,调用main函数 if __name__ == "__main__": main() # 脚本入口,当文件被直接运行时调用main函数 ``` -------------------------------- ### DeleteBucketQosInfo Request Example Source: https://help.aliyun.com/zh/oss/developer-reference/api-delete-bucket-qos-info An example of an HTTP DELETE request to remove QoS configuration for a bucket. Note the Authorization header format which includes credential and signature. ```http DELETE /?qosInfo HTTP/1.1 Host: oss-example.oss-cn-hangzhou.aliyuncs.com Date: Fri, 27 Dec 2024 03:21:12 GMT Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e ``` -------------------------------- ### Put Bucket Logging (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for configuring access logging for an OSS bucket using the Python SDK V2. This logs all requests made to the bucket. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Set logging configuration logging_config = { 'LoggingEnabled': { 'TargetBucket': 'your_log_bucket_name', 'TargetPrefix': 'access-logs/' } } api.put_bucket_logging('your_bucket_name', logging_config) print('Bucket logging configuration set successfully.') ``` -------------------------------- ### AppendObject Response Example with Versioning Source: https://help.aliyun.com/zh/oss/developer-reference/appendobject This response example for AppendObject on a versioned bucket includes the x-oss-version-id header. Other relevant headers like ETag and x-oss-next-append-position are also present. ```HTTP HTTP/1.1 200 OK Date: Tue, 09 Apr 2019 03:59:33 GMT ETag: "2776271A4A09D82CA518AC5C0000****" Connection: keep-alive Content-Length: 0 Server: AliyunOSS x-oss-version-id: CAEQGhiBgIC_k6aV5RgiIGI3YTY2ZmMzYWJlMzQ3YjM4YTljOTk5YjUyZGF**** x-oss-hash-crc64ecma: 3231342946509354535 x-oss-next-append-position: 47 x-oss-request-id: 5CAC18A5B7AEADE01700**** ``` -------------------------------- ### Configure OSS Client with Financial Cloud Endpoint Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version This snippet provides an example for configuring the OSS client to use endpoints specific to Alibaba Cloud's financial cloud. It shows how to set the region and endpoint for a financial cloud environment. Ensure placeholders are replaced with actual values. ```python import alibabacloud_oss_v2 as oss def main(): # 从环境变量中加载凭证信息,用于身份验证 credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() # 加载SDK的默认配置,并设置凭证提供者 cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # 填写Region和Endpoint # 填写Bucket所在地域。以华东1 金融云为例,Region填写为cn-hangzhou-finance cfg.region = 'cn-hangzhou-finance' # 填写Bucket所在地域对应的内网Endpoint。以华东1 金融云为例,Endpoint填写为'https://oss-cn-hzjbp-a-internal.aliyuncs.com', # 如需指定为http协议,请在指定域名时填写为'http://oss-cn-hzjbp-a-internal.aliyuncs.com' cfg.endpoint = 'https://oss-cn-hzjbp-a-internal.aliyuncs.com' # 使用配置好的信息创建OSS客户端 client = oss.Client(cfg) # 使用创建好的client执行后续操作... # 当此脚本被直接运行时,调用main函数 if __name__ == "__main__": main() # 脚本入口,当文件被直接运行时调用main函数 ``` -------------------------------- ### Put Bucket Inventory (Python SDK V2) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Example for configuring an inventory task for an OSS bucket using the Python SDK V2. Inventory provides a list of all objects in the bucket and their metadata. ```python from oss_api import OssApi # Initialize OssApi with your credentials and endpoint api = OssApi('your_access_key_id', 'your_access_key_secret', 'your_endpoint') # Set inventory configuration inventory_config = { 'InventoryConfiguration': { 'Id': 'inventory-all-objects', 'IsEnabled': True, 'Destination': { 'OssBucketDestination': { 'Bucket': 'your_inventory_bucket_name', 'Prefix': 'inventory/', 'Format': 'CSV' } }, 'Schedule': {'Frequency': 'Daily'} } } api.put_bucket_inventory('your_bucket_name', inventory_config) print('Bucket inventory configuration set successfully.') ``` -------------------------------- ### Abort Multipart Upload Request Example Source: https://help.aliyun.com/zh/oss/developer-reference/abortmultipartupload This example shows how to make an HTTP DELETE request to abort a multipart upload. It includes necessary headers such as Host, Date, and Authorization. ```APIDOC ## DELETE /multipart.data?uploadId=YOUR_UPLOAD_ID ### Description Aborts a multipart upload. Any parts previously uploaded using the upload ID are no longer available to be listed or completed. You must know the upload ID to be able to abort the upload. ### Method DELETE ### Endpoint `/multipart.data?uploadId=` ### Parameters #### Query Parameters - **uploadId** (string) - Required - The ID of the multipart upload to abort. ### Request Example ```http DELETE /multipart.data?uploadId=0004B9895DBBB6E**** HTTP/1.1 Host: oss-example.oss-cn-hangzhou.aliyuncs.com Date: Wed, 22 Feb 2012 08:32:21 GMT Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e ``` ### Response #### Success Response (204) - **No Content**: The upload was successfully aborted. #### Response Example ```http HTTP/1.1 204 Server: AliyunOSS Content-length: 0 Connection: keep-alive x-oss-request-id: 059a22ba-6ba9-daed-5f3a-e48027df**** Date: Wed, 22 Feb 2012 08:32:21 GMT x-oss-server-time: 86 ``` ### Error Codes - **NoSuchUpload**: HTTP Status Code 404 - The specified upload ID does not exist. ``` -------------------------------- ### Configure Access Keys via Environment Variables (Linux/macOS - Bash) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Set up AccessKey ID and Secret for OSS authentication by exporting environment variables and appending them to ~/.bashrc. Ensure changes are sourced. ```bash echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc ``` ```bash source ~/.bashrc ``` ```bash echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET ``` -------------------------------- ### AppendObject Request Example Source: https://help.aliyun.com/zh/oss/developer-reference/appendobject This is a standard request example for the AppendObject operation. Ensure correct Host, Date, Content-Type, and Authorization headers are included. The object data is sent in the request body. ```HTTP POST /oss.jpg?append&position=0 HTTP/1.1 Host: oss-example.oss.aliyuncs.com Cache-control: no-cache Expires: Wed, 08 Jul 2015 16:57:01 GMT x-oss-storage-class: Archive Content-Disposition: attachment;filename=oss_download.jpg Date: Wed, 08 Jul 2015 06:57:01 GMT Content-Type: image/jpg Content-Length: 1717 Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,AdditionalHeaders=content-disposition;content-length,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e [1717 bytes of object data] ``` -------------------------------- ### Initialize OSS Client with Hardcoded STS Credentials (Python) Source: https://help.aliyun.com/zh/oss/developer-reference/2-0-manual-preview-version Initialize an OSS client in Python by explicitly providing STS temporary credentials. This method is for testing purposes only and should not be used in production. ```python import alibabacloud_oss_v2 as oss def main(): # 填写获取的临时访问密钥AccessKey ID和AccessKey Secret,非阿里云账号AccessKey ID和AccessKey Secret。 # 请注意区分STS服务获取的Access Key ID是以STS开头,。。 sts_access_key_id = 'STS.****************' sts_access_key_secret = 'yourAccessKeySecret' # 填写获取的STS安全令牌(SecurityToken)。 sts_security_token = 'yourSecurityToken' # 创建静态凭证提供者,显式设置临时访问密钥AccessKey ID和AccessKey Secret,以及STS安全令牌 credentials_provider = oss.credentials.StaticCredentialsProvider( access_key_id=sts_access_key_id, access_key_secret=sts_access_key_secret, security_token=sts_security_token, ) # 加载SDK的默认配置,并设置凭证提供者 cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # 填写Bucket所在地域 cfg.region = '' # 使用配置好的信息创建OSS客户端 client = oss.Client(cfg) # 使用创建好的client执行后续操作... # 当此脚本被直接运行时,调用main函数 if __name__ == "__main__": main() # 脚本入口,当文件被直接运行时调用main函数 ``` -------------------------------- ### HTTP Request Example for AbortMultipartUpload Source: https://help.aliyun.com/zh/oss/developer-reference/abortmultipartupload This example shows the HTTP request to abort a multipart upload. Ensure you replace placeholder values with your actual upload ID, host, and authorization credentials. ```http DELETE /multipart.data?&uploadId=0004B9895DBBB6E**** HTTP/1.1 Host: oss-example.oss-cn-hangzhou.aliyuncs.com Date: Wed, 22 Feb 2012 08:32:21 GMT Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e ``` -------------------------------- ### CreateAccessPoint Source: https://help.aliyun.com/zh/oss/developer-reference/list-of-operations-by-function Creates an access point for OSS resources. ```APIDOC ## POST CreateAccessPoint ### Description Creates a new access point. ### Method POST ### Endpoint CreateAccessPoint ```