### Basic OSS Client Setup Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/0-index.md Configure and create an OSS client instance. This example uses environment variables for credentials and specifies the region. ```python import alibabacloud_oss_v2 as oss # Create configuration config = oss.config.load_default() config.credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() config.region = "cn-hangzhou" # Create client client = oss.Client(config) ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/2-configuration.md This example demonstrates how to create a fully customized configuration object for the OSS SDK v2, including network, endpoint, security, and retry settings. ```APIDOC ## Complete Configuration Example ```python import alibabacloud_oss_v2 as oss from datetime import timedelta # Create custom configuration config = oss.Config( # Essential settings region="cn-hangzhou", credentials_provider=oss.credentials.StaticCredentialsProvider( access_key_id="your-access-key-id", access_key_secret="your-access-key-secret", security_token=None # For STS tokens ), # Network settings connect_timeout=15, readwrite_timeout=30, # Endpoint settings endpoint="oss-cn-hangzhou.aliyuncs.com", use_cname=False, use_path_style=False, # Acceleration use_dualstack_endpoint=False, use_accelerate_endpoint=False, use_internal_endpoint=False, # Security disable_ssl=False, insecure_skip_verify=False, enabled_redirect=True, # Integrity checking disable_upload_crc64_check=False, disable_download_crc64_check=False, # Signing signature_version="v4", additional_headers=["x-oss-custom-header"], # Retry behavior retry_max_attempts=3, # User identification user_agent="my-app/1.0.0" ) # Create client client = oss.Client(config) ``` ``` -------------------------------- ### Example Usage of Credentials Class Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/4-credentials.md Demonstrates how to instantiate the Credentials class and check its validity. This example shows setting up credentials with an expiration time and verifying their presence and validity. ```python import alibabacloud_oss_v2 as oss from datetime import datetime, timezone, timedelta creds = oss.types.Credentials( access_key_id="AKIAIOSFODNN7EXAMPLE", access_key_secret="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", security_token="AQoDYXdzEJr...", expiration=datetime.now(timezone.utc) + timedelta(hours=1) ) if creds.has_keys(): print("Credentials are set") if not creds.is_expired(): print("Credentials are still valid") ``` -------------------------------- ### Initialize OSS Client Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/README.md Demonstrates how to initialize the OSS client with basic configuration. Ensure you have the SDK installed. ```python from alibabacloud_oss_v2.client import OssClient # Initialize the client with your endpoint and access key ID/secret client = OssClient(endpoint="oss-cn-hangzhou.aliyuncs.com", access_key_id="YOUR_ACCESS_KEY_ID", access_key_secret="YOUR_ACCESS_KEY_SECRET") ``` -------------------------------- ### Install OSS SDK v2 from source Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/README.md Install the OSS SDK for Python v2 directly from the unzipped installer package. ```bash sudo python setup.py install ``` -------------------------------- ### Install Alibaba Cloud OSS Python SDK v2 Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/0-index.md Install the SDK using pip. Ensure you have Python 3.8 or higher and the specified dependency versions. ```bash pip install alibabacloud-oss-v2 ``` -------------------------------- ### Install OSS SDK v2 via pip Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/README.md Install the beta version of the OSS SDK for Python v2 using pip. ```bash pip install alibabacloud-oss-v2 ``` -------------------------------- ### OSS Client Configuration Examples Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/DEVGUIDE-CN.md Demonstrates various ways to configure the OSS client using different parameters. These examples show how to set region, credentials provider, endpoint, HTTP client, retry attempts, retryer, timeouts, SSL verification, redirects, proxy, signature version, path-style access, custom domains, dualstack, accelerate, internal endpoints, and disable CRC checks. ```python oss.config.Config(region="cn-hangzhou") ``` ```python oss.config.Config(credentials_provider=provider) ``` ```python oss.config.Config(endpoint="oss-cn-hanghzou.aliyuncs.com") ``` ```python oss.config.Config(http_client=customClient) ``` ```python oss.config.Config(retry_max_attempts=5) ``` ```python oss.config.Config(retryer=customRetryer) ``` ```python oss.config.Config(connect_timeout=20) ``` ```python oss.config.Config(readwrite_timeout=30) ``` ```python oss.config.Config(insecure_skip_verify=true) ``` ```python oss.config.Config(enabled_redirect=true) ``` ```python oss.config.Config(proxy_host="http://user:passswd@proxy.example-***.com") ``` ```python oss.config.Config(signature_version="v1") ``` ```python oss.config.Config(disable_ssl=true) ``` ```python oss.config.Config(use_path_style=true) ``` ```python oss.config.Config(use_cname=true) ``` ```python oss.config.Config(use_dualstack_endpoint=true) ``` ```python oss.config.Config(use_accelerate_endpoint=true) ``` ```python oss.config.Config(use_internal_endpoint=true) ``` ```python oss.config.Config(disable_upload_crc64_check=true) ``` ```python oss.config.Config(disable_download_crc64_check=true) ``` ```python oss.config.Config(additional_headers=["content-length"]) ``` ```python oss.config.Config(user_agent="user identifier") ``` -------------------------------- ### Upload File Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/5-uploader-downloader-copier.md Demonstrates uploading a local file to OSS with custom part size, parallel threads, and checkpoint enabled. ```python import alibabacloud_oss_v2 as oss client = oss.Client(config) uploader = oss.Uploader(client) result = uploader.upload_file( oss.PutObjectRequest( bucket="my-bucket", key="large-file.zip" ), filepath="/local/path/large-file.zip", part_size=10*1024*1024, # 10 MiB parts parallel_num=5, enable_checkpoint=True, checkpoint_dir="/tmp/checkpoints" ) print(f"Upload complete. ETag: {result.etag}") ``` -------------------------------- ### Upload From Stream Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/5-uploader-downloader-copier.md Shows how to upload data from a file stream to OSS with a specified number of parallel threads. ```python with open("large-file.bin", "rb") as f: result = uploader.upload_from( oss.PutObjectRequest( bucket="my-bucket", key="uploaded-file.bin" ), body=f, parallel_num=3 ) ``` -------------------------------- ### ListBucketsPaginator Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/6-paginators.md Iterate over all buckets in your Alibaba Cloud account using the ListBucketsPaginator. Ensure you have initialized the OSS client with your configuration. ```python import alibabacloud_oss_v2 as oss client = oss.Client(config) paginator = client.list_buckets_paginator() for page in paginator.iter_page(oss.ListBucketsRequest()): for bucket in page.buckets: print(f"Bucket: {bucket.name}") print(f" Location: {bucket.location}") print(f" Created: {bucket.creation_date}") ``` -------------------------------- ### OSS SDK v2 Complete Utility Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/8-utilities.md Demonstrates various utility functions: reading from an object like a file, appending data to an object, generating a presigned URL for an object, computing a CRC64 checksum, and downloading a file with a progress callback. Ensure the environment variables for credentials and the region are set. ```python import alibabacloud_oss_v2 as oss from datetime import timedelta # Setup config = oss.config.load_default() config.credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() config.region = "cn-hangzhou" client = oss.Client(config) # 1. Read object as file with oss.ReadOnlyFile(bucket="my-bucket", key="data.bin", client=client) as f: # Seek to position f.seek(1000) # Read data chunk = f.read(512) print(f"Read {len(chunk)} bytes from position 1000") # 2. Append to object with oss.AppendOnlyFile(bucket="my-bucket", key="log.txt", client=client) as f: f.write(b"New log entry\n") print(f"Appended at position {f.tell()}") # 3. Generate presigned URL presign_result = client.presign( oss.GetObjectRequest(bucket="my-bucket", key="file.txt"), expires=timedelta(hours=2) ) print(f"Presigned URL: {presign_result.url}") # 4. Compute CRC64 crc = oss.Crc64.update(0, b"sample data") print(f"CRC64: {crc}") # 5. Download with progress class ProgressCallback(oss.Progress): def progress(self, consumed: int, total: int) -> None: pct = (consumed / total * 100) if total > 0 else 0 print(f"\rDownload: {pct:.1f}%", end="") downloader = oss.Downloader(client) result = downloader.download_file( oss.GetObjectRequest(bucket="my-bucket", key="file.zip"), "/local/file.zip" ) print(f"\nDownloaded {result.written} bytes") ``` -------------------------------- ### Multi-Source Credential Provider Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/4-credentials.md Implement a fallback mechanism for obtaining credentials by trying environment variables, static credentials, and anonymous access in order. This ensures a robust way to initialize the OSS client. ```python import alibabacloud_oss_v2 as oss def get_credentials(): """Try multiple credential sources in order.""" # Try environment variables first try: return oss.credentials.EnvironmentVariableCredentialsProvider() except oss.exceptions.CredentialsEmptyError: pass # Fall back to static credentials try: return oss.credentials.StaticCredentialsProvider( access_key_id="default-key-id", access_key_secret="default-key-secret" ) except: pass # Last resort: anonymous access return oss.credentials.AnonymousCredentialsProvider() try: credentials_provider = get_credentials() config = oss.config.load_default() config.credentials_provider = credentials_provider config.region = "cn-hangzhou" client = oss.Client(config) print("Client created successfully") except Exception as e: print(f"Failed to create client: {e}") ``` -------------------------------- ### List All Objects with Prefix Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/6-paginators.md Iterate through all objects in a bucket that match a specific prefix. This example collects all matching objects into a list and prints their keys. ```python import alibabacloud_oss_v2 as oss client = oss.Client(config) paginator = client.list_objects_v2_paginator() all_objects = [] for page in paginator.iter_page(oss.ListObjectsV2Request( bucket="my-bucket", prefix="logs/2024/" )): all_objects.extend(page.contents) print(f"Total objects: {len(all_objects)}") for obj in all_objects: print(f" {obj.key}") ``` -------------------------------- ### Example Usage of ListMultipartUploadsPaginator Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/6-paginators.md Demonstrates how to use the ListMultipartUploadsPaginator to iterate through multipart uploads for a specified bucket and print details of each upload. ```python import alibabacloud_oss_v2 as oss client = oss.Client(config) paginator = client.list_multipart_uploads_paginator() for page in paginator.iter_page(oss.ListMultipartUploadsRequest( bucket="my-bucket" )): for upload in page.uploads: print(f"Upload: {upload.key}") print(f" ID: {upload.upload_id}") print(f" Initiated: {upload.initiated}") ``` -------------------------------- ### Complete Multipart Upload with Checkpoints and Parallel Parts Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/5-uploader-downloader-copier.md This example demonstrates a complete multipart upload using the Aliyun OSS SDK v2 for Python. It configures the client, enables checkpoints for resumability, and specifies part size and parallel upload threads for efficiency. Error handling for `oss.UploadError` is included, which can provide the `upload_id` for resuming interrupted uploads. ```python import alibabacloud_oss_v2 as oss import os # Setup config = oss.config.load_default() config.credentials_provider = oss.credentials.StaticCredentialsProvider( access_key_id="your-key-id", access_key_secret="your-key-secret" ) config.region = "cn-hangzhou" client = oss.Client(config) uploader = oss.Uploader(client) # Upload with checkpoints and parallel parts try: result = uploader.upload_file( oss.PutObjectRequest( bucket="my-bucket", key="dataset-2024.tar.gz" ), filepath="/data/dataset-2024.tar.gz", part_size=20*1024*1024, # 20 MiB parts parallel_num=8, # 8 concurrent parts enable_checkpoint=True, checkpoint_dir="/tmp/uploads" ) print(f"Upload successful") print(f" ETag: {result.etag}") print(f" Version ID: {result.version_id}") print(f" CRC64: {result.hash_crc64}") except oss.UploadError as e: print(f"Upload failed: {e.unwrap()}") print(f"Upload ID: {e.upload_id}") # Checkpoint file saved; can retry upload ``` -------------------------------- ### CopyObject Request Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/5-uploader-downloader-copier.md Demonstrates how to use the copy_object method to copy an object, specifying parameters like part_size, parallel_num, and checkpoint options. ```python import alibabacloud_oss_v2 as oss client = oss.Client(config) copier = oss.Copier(client) result = copier.copy_object( oss.CopyObjectRequest( bucket="dest-bucket", key="destination-key", source_bucket="source-bucket", source_key="source-key" ), part_size=64*1024*1024, parallel_num=5, enable_checkpoint=True, checkpoint_dir="/tmp/checkpoints" ) print(f"Copy complete. ETag: {result.etag}") ``` -------------------------------- ### Get Bucket Information with OSS Python SDK Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/1-client-api.md Use this to query detailed information about an OSS bucket. ```python def get_bucket_info(self, request: models.GetBucketInfoRequest, **kwargs) -> models.GetBucketInfoResult: """Queries detailed information about a bucket.""" ``` -------------------------------- ### Complete Parallel Download Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/5-uploader-downloader-copier.md Download a large file in parallel using multiple parts and enable checkpointing to resume interrupted downloads. Configure part size, concurrency, and checkpoint directory. ```python import alibabacloud_oss_v2 as oss # Setup config = oss.config.load_default() config.credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() config.region = "cn-hangzhou" client = oss.Client(config) downloader = oss.Downloader(client) # Download with parallel parts and checkpoints try: result = downloader.download_file( oss.GetObjectRequest( bucket="my-bucket", key="large-backup.zip" ), filepath="/backups/large-backup.zip", part_size=50*1024*1024, # 50 MiB parts parallel_num=4, # 4 concurrent parts enable_checkpoint=True, checkpoint_dir="/tmp/downloads", verify_data=True # Verify CRC64 on resume ) print(f"Download successful: {result.written} bytes") except oss.DownloadError as e: print(f"Download failed: {e.unwrap()}") # Checkpoint file saved; can retry download ``` -------------------------------- ### EnvironmentVariableCredentialsProvider Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/4-credentials.md Loads credentials from environment variables (OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, OSS_SESSION_TOKEN). Useful for containerized environments. Raises CredentialsEmptyError if required variables are not set. ```bash # Set environment variables export OSS_ACCESS_KEY_ID="your-access-key-id" export OSS_ACCESS_KEY_SECRET="your-access-key-secret" export OSS_SESSION_TOKEN="optional-session-token" ``` ```python import alibabacloud_oss_v2 as oss try: credentials = oss.credentials.EnvironmentVariableCredentialsProvider() config = oss.config.load_default() config.credentials_provider = credentials config.region = "cn-hangzhou" client = oss.Client(config) except oss.exceptions.CredentialsEmptyError: print("Error: OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET must be set") ``` -------------------------------- ### Iterate Objects with ListObjectsV2 Paginator Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/1-client-api.md Example demonstrating how to use the `list_objects_v2_paginator` to iterate through objects in a bucket and print their keys. Ensure the `oss` module is imported. ```python paginator = client.list_objects_v2_paginator() for page in paginator.iter_page(oss.ListObjectsV2Request(bucket="my-bucket")): for obj in page.contents: print(f'Key: {obj.key}') ``` -------------------------------- ### CredentialsEmptyError Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/7-exceptions.md Raised when credentials are required but not provided or are empty. Use this when environment variables OSS_ACCESS_KEY_ID or OSS_ACCESS_KEY_SECRET are not set when using EnvironmentVariableCredentialsProvider. ```python import alibabacloud_oss_v2 as oss try: credentials = oss.credentials.EnvironmentVariableCredentialsProvider() except oss.exceptions.CredentialsEmptyError: print("Error: Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables") ``` -------------------------------- ### Example Usage of ListObjectsV2Paginator Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/6-paginators.md Demonstrates how to use the `ListObjectsV2Paginator` to iterate through objects in a bucket. It initializes the client and paginator, then loops through pages and object contents, printing the key and last modified date. ```python import alibabacloud_oss_v2 as oss client = oss.Client(config) paginator = client.list_objects_v2_paginator() for page in paginator.iter_page(oss.ListObjectsV2Request( bucket="my-bucket", prefix="documents/" )): for obj in page.contents: print(f"{obj.key}: {obj.last_modified}") ``` -------------------------------- ### Example Usage of ListObjectVersionsPaginator Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/6-paginators.md Shows how to use the `ListObjectVersionsPaginator` to retrieve object versions. It initializes the client and paginator, then iterates through pages, printing details for both object versions and delete markers. ```python import alibabacloud_oss_v2 as oss client = oss.Client(config) paginator = client.list_object_versions_paginator() for page in paginator.iter_page(oss.ListObjectVersionsRequest( bucket="versioned-bucket" )): for obj in page.versions: print(f"{obj.key} (version {obj.version_id}): {obj.last_modified}") for marker in page.delete_markers: print(f"{marker.key} (deleted, version {marker.version_id})") ``` -------------------------------- ### Count Objects by Prefix Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/6-paginators.md Count the number of objects in a bucket for each top-level prefix. This example iterates through all objects and categorizes them by their first path segment. ```python import alibabacloud_oss_v2 as oss client = oss.Client(config) paginator = client.list_objects_v2_paginator() prefix_counts = {} for page in paginator.iter_page(oss.ListObjectsV2Request( bucket="my-bucket" )): for obj in page.contents: prefix = obj.key.split('/')[0] if '/' in obj.key else "root" prefix_counts[prefix] = prefix_counts.get(prefix, 0) + 1 for prefix, count in sorted(prefix_counts.items(), key=lambda x: -x[1]): print(f"{prefix}: {count} objects") ``` -------------------------------- ### Handling FileNotExist Exception Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/7-exceptions.md Example of how to catch and handle the FileNotExist exception when attempting to upload a file that does not exist locally. It prints a user-friendly message. ```python try: result = client.put_object_from_file( oss.PutObjectRequest(bucket="my-bucket", key="file.txt"), "/nonexistent/file.txt" ) except oss.exceptions.FileNotExist as e: print(f"File not found: {e}") ``` -------------------------------- ### ListPartsPaginator Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/6-paginators.md Iterate over parts of an in-progress multipart upload using the ListPartsPaginator. You must provide the bucket name, key, and upload ID for the multipart upload. ```python import alibabacloud_oss_v2 as oss client = oss.Client(config) paginator = client.list_parts_paginator() for page in paginator.iter_page(oss.ListPartsRequest( bucket="my-bucket", key="large-file.zip", upload_id="upload-id-from-initiate" )): for part in page.parts: print(f"Part {part.part_number}: {part.size} bytes, ETag: {part.etag}") ``` -------------------------------- ### ReadOnlyFile Example Usage Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/8-utilities.md Demonstrates how to use the ReadOnlyFile class to read, seek, and manage OSS objects like regular files. Supports context manager for automatic closing. ```python import alibabacloud_oss_v2 as oss client = oss.Client(config) file = oss.ReadOnlyFile( bucket="my-bucket", key="large-file.bin", client=client ) # Read like a normal file data = file.read(1024) # Seek to position file.seek(10000) data = file.read(1024) # Get position pos = file.tell() # Close when done file.close() # Or use context manager with oss.ReadOnlyFile(bucket="my-bucket", key="file.bin", client=client) as f: data = f.read() ``` -------------------------------- ### AppendOnlyFile Example Usage Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/8-utilities.md Demonstrates how to use the AppendOnlyFile class to write data in append mode to an OSS object. Supports context manager for automatic closing. ```python import alibabacloud_oss_v2 as oss client = oss.Client(config) file = oss.AppendOnlyFile( bucket="my-bucket", key="log-file.txt", client=client ) # Append data file.write(b"Log entry 1\n") file.write(b"Log entry 2\n") # Close when done file.close() ``` -------------------------------- ### Initialize OSS Client Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/1-client-api.md Demonstrates how to initialize the OSS Client using environment variables for credentials and default configuration loading. Ensure your environment variables for OSS credentials are set. ```python import alibabacloud_oss_v2 as oss credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider cfg.region = "cn-hangzhou" client = oss.Client(cfg) ``` -------------------------------- ### Get Object Tags Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Retrieves the tags associated with a specific object. ```APIDOC ## Get Object Tags ### Description Retrieves the tags associated with a specific object. ### Method `get_object_tagging(request: GetObjectTaggingRequest)` ### Parameters #### Request Body - **bucket** (string) - Required - The name of the bucket. - **key** (string) - Required - The object key. ### Request Example ```python result = client.get_object_tagging(oss.GetObjectTaggingRequest( bucket="my-bucket", key="file.txt" )) for tag in result.tagging: print(f"{tag.key}: {tag.value}") ``` ### Response - **tagging** (list) - A list of tag objects, each containing a key-value pair for a tag. ``` -------------------------------- ### Get Bucket Location Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Retrieves the geographical location where the specified bucket is hosted. ```APIDOC ## Get Bucket Location ### Description Retrieves the region or location where the bucket is physically stored. ### Method `client.get_bucket_location()` ### Parameters - `oss.GetBucketLocationRequest`: - `bucket` (str): The name of the bucket. ### Request Example ```python result = client.get_bucket_location(oss.GetBucketLocationRequest(bucket="my-bucket")) print(result.location) ``` ### Response #### Success Response (200) - `location` (str): The location of the bucket. ``` -------------------------------- ### OSS Configuration Options Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Shows how to initialize the OSS client with various configuration options, including region, endpoint, timeouts, and network settings. ```python config = oss.Config( region="cn-hangzhou", endpoint="custom.aliyuncs.com", connect_timeout=15, readwrite_timeout=60, disable_ssl=False, use_cname=False, use_path_style=False, use_dualstack_endpoint=False, use_accelerate_endpoint=False, use_internal_endpoint=False, proxy_host="http://proxy:3128", disable_upload_crc64_check=False, disable_download_crc64_check=False, retry_max_attempts=3, signature_version="v4" ) ``` -------------------------------- ### Get Object Tags Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Retrieves the tags associated with a specific object in an OSS bucket. ```python result = client.get_object_tagging(oss.GetObjectTaggingRequest( bucket="my-bucket", key="file.txt" )) for tag in result.tagging: print(f"{tag.key}: {tag.value}") ``` -------------------------------- ### Initialize OSS Client Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/0-index.md Instantiate the main client class with a configuration object. This is the primary entry point for all SDK operations. ```python client = oss.Client(config) ``` -------------------------------- ### Get Bucket ACL Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Retrieves the Access Control List (ACL) configuration for a specified bucket. ```APIDOC ## Get Bucket ACL ### Description Retrieves the current Access Control List (ACL) configuration of a bucket. ### Method `client.get_bucket_acl()` ### Parameters - `oss.GetBucketAclRequest`: - `bucket` (str): The name of the bucket. ### Request Example ```python result = client.get_bucket_acl(oss.GetBucketAclRequest(bucket="my-bucket")) print(result.acl) ``` ### Response #### Success Response (200) - `acl` (str): The ACL setting of the bucket. ``` -------------------------------- ### Presigned URL Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Generates a presigned URL for an object, granting temporary access for GET requests. ```APIDOC ## Presigned URL ### Description Generates a presigned URL for an object, granting temporary access for GET requests. ### Method `presign(request: GetObjectRequest, expires: timedelta)` ### Parameters #### Request Body - **bucket** (string) - Required - The name of the bucket. - **key** (string) - Required - The object key. - **expires** (timedelta) - Required - The duration for which the URL will be valid. ### Request Example ```python from datetime import timedelta presign = client.presign( oss.GetObjectRequest(bucket="my-bucket", key="file.txt"), expires=timedelta(hours=1) ) print(presign.url) ``` ### Response - **url** (string) - The generated presigned URL. ``` -------------------------------- ### Initialize OSS Client with Environment Credentials Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/2-configuration.md Use `EnvironmentVariableCredentialsProvider` to load credentials from environment variables. Load default configuration, set the credentials provider and region, then create the OSS client. ```python import alibabacloud_oss_v2 as oss credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() config = oss.config.load_default() config.credentials_provider = credentials_provider config.region = "cn-hangzhou" client = oss.Client(config) ``` -------------------------------- ### Get Bucket Statistics Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Retrieves statistical information about a bucket, including storage size and object count. ```APIDOC ## Get Bucket Statistics ### Description Fetches statistics for a bucket, such as total storage size and the number of objects it contains. ### Method `client.get_bucket_stat()` ### Parameters - `oss.GetBucketStatRequest`: - `bucket` (str): The name of the bucket. ### Request Example ```python result = client.get_bucket_stat(oss.GetBucketStatRequest(bucket="my-bucket")) print(f"Storage: {result.storage_size_in_bytes} bytes") print(f"Objects: {result.object_count}") ``` ### Response #### Success Response (200) - `storage_size_in_bytes` (int): The total storage size in bytes. - `object_count` (int): The total number of objects in the bucket. ``` -------------------------------- ### Get Object Metadata Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Retrieves metadata for a specific object in an OSS bucket, such as its size and content type. ```python result = client.head_object(oss.HeadObjectRequest( bucket="my-bucket", key="file.txt" )) print(f"Size: {result.content_length}") print(f"Type: {result.content_type}") ``` -------------------------------- ### Initialize Downloader Class Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/5-uploader-downloader-copier.md Instantiate the Downloader class with a client that implements head_object and get_object. Extra keyword arguments can be passed for initialization. ```python class Downloader: """Downloader for handling objects for downloads.""" def __init__( self, client: DownloadAPIClient, **kwargs: Any ) -> None: """ Args: client (DownloadAPIClient): A client implementing head_object and get_object. kwargs: Extra keyword arguments for initialization. """ ``` -------------------------------- ### AnonymousCredentialsProvider Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/4-credentials.md Use this provider for anonymous access to publicly readable buckets or objects without requiring credentials. ```python import alibabacloud_oss_v2 as oss config = oss.config.load_default() config.credentials_provider = oss.credentials.AnonymousCredentialsProvider() config.region = "cn-hangzhou" client = oss.Client(config) # Can now access public objects result = client.get_object(oss.GetObjectRequest( bucket="public-bucket", key="public-file.txt" )) ``` -------------------------------- ### Get Bucket Location with OSS Python SDK Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/1-client-api.md Use this to query the geographic location (region) of an OSS bucket. ```python def get_bucket_location(self, request: models.GetBucketLocationRequest, **kwargs) -> models.GetBucketLocationResult: """Queries the geographic location (region) of a bucket.""" ``` -------------------------------- ### Load Default Configuration Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/2-configuration.md Use this to create a Config instance with sensible defaults for immediate use. Set credentials and region after loading. ```python import alibabacloud_oss_v2 as oss # Load default configuration config = oss.config.load_default() # Set credentials and region credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() config.credentials_provider = credentials_provider config.region = "cn-hangzhou" # Create client client = oss.Client(config) ``` -------------------------------- ### Async OSS Client Operations Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/8-utilities.md Demonstrates how to initialize and use the asynchronous OSS client for operations like uploading objects. Requires environment variables for credentials and a specified region. ```python import asyncio import alibabacloud_oss_v2 as oss async def main(): config = oss.config.load_default() config.credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() config.region = "cn-hangzhou" client = oss.aio.AsyncClient(config) # Async operations result = await client.put_object(oss.PutObjectRequest( bucket="my-bucket", key="file.txt", body=b"content" )) print(f"ETag: {result.etag}") asyncio.run(main()) ``` -------------------------------- ### Use Environment Variable Credentials Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/README.md Initializes the OSS client using credentials from environment variables. Ensure ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set. ```python from alibabacloud_oss_v2.client import OssClient from alibabacloud_oss_v2.models import Config # Initialize client using environment variables for credentials # Ensure ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set in your environment config = Config( endpoint="oss-cn-hangzhou.aliyuncs.com" ) client = OssClient(config=config) ``` -------------------------------- ### Get Object Metadata Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Retrieves the metadata of an object without downloading its content. Useful for checking size, type, etc. ```APIDOC ## Get Object Metadata ### Description Retrieves the metadata of an object without downloading its content. Useful for checking size, type, etc. ### Method `head_object(request: HeadObjectRequest)` ### Parameters #### Request Body - **bucket** (string) - Required - The name of the bucket. - **key** (string) - Required - The object key. ### Request Example ```python result = client.head_object(oss.HeadObjectRequest( bucket="my-bucket", key="file.txt" )) print(f"Size: {result.content_length}") print(f"Type: {result.content_type}") ``` ### Response - **content_length** (int) - The size of the object in bytes. - **content_type** (string) - The MIME type of the object. ``` -------------------------------- ### Instantiate Copier with Custom Part Size Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/DEVGUIDE-CN.md Demonstrates how to instantiate the Copier with a custom part size for copy operations. ```python copier = client.copier( part_size=100 * 1024 * 1024, ) ``` -------------------------------- ### CredentialsProviderFunc Initialization Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/4-credentials.md Initializes CredentialsProviderFunc with a callable function that returns Credentials. The function should have a signature of `() -> Credentials`. ```python class CredentialsProviderFunc(CredentialsProvider): """Provides a helper wrapping a function value to satisfy the CredentialsProvider interface.""" def __init__( self, func: Callable, ) -> None: """ Args: func (Callable): A function that returns a Credentials instance when called. """ ``` -------------------------------- ### Get Bucket ACL with OSS Python SDK Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/1-client-api.md Use this to query the current Access Control List (ACL) of an OSS bucket. ```python def get_bucket_acl(self, request: models.GetBucketAclRequest, **kwargs) -> models.GetBucketAclResult: """Queries the ACL of a bucket.""" ``` -------------------------------- ### OSS Credentials Providers Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Demonstrates how to configure credentials for the OSS client using static keys, environment variables, anonymous access, or a custom function. ```python # Static credentials oss.credentials.StaticCredentialsProvider( access_key_id="...", access_key_secret="..." ) ``` ```python # Environment variables (OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET) oss.credentials.EnvironmentVariableCredentialsProvider() ``` ```python # Anonymous access oss.credentials.AnonymousCredentialsProvider() ``` ```python # Custom function oss.credentials.CredentialsProviderFunc(func=lambda: oss.types.Credentials(...)) ``` -------------------------------- ### Define ObjectNameInvalidError Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/7-exceptions.md Raised when an object key is invalid. Object keys have a maximum length of 1024 bytes, cannot start with '/', and cannot be empty. ```python class ObjectNameInvalidError(BaseError): """Param Invalid Error.""" fmt = 'Object name is invalid.' ``` -------------------------------- ### Read Remaining Data from a Specific Position Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/DEVGUIDE-CN.md Reads the remaining data of an object starting from a specified position using the seek method. ```python client = oss.Client(cfg) rf: oss.ReadOnlyFile = None with client.open_file("example_bucket", "example_key") as f: rf = f f.seek(123, os.SEEK_SET) copied_stream = io.BytesIO(rf.read()) print(f'written: {len(copied_stream.getvalue())}') ``` -------------------------------- ### Client Initialization Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/1-client-api.md Initializes the Client with a configuration object. The configuration includes credentials, region, and endpoint settings. ```APIDOC ## Client Initialization ### Description Initializes the Client with a configuration object. The configuration includes credentials, region, and endpoint settings. ### Constructor `__init__(self, config: Config, **kwargs) -> None` ### Parameters #### Constructor Parameters - **config** (Config) - Yes - Description: Configuration object that specifies credentials provider, region, endpoint, and connection settings ``` -------------------------------- ### Create Bucket using OSS SDK Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/DEVGUIDE-CN.md This snippet demonstrates how to create a new OSS bucket with specified ACL and storage class. It requires an initialized OSS client and a bucket name. ```python client = oss.Client(cfg) result = client.put_bucket(oss.PutBucketRequest( bucket="example_bucket", acl='private', create_bucket_configuration=oss.CreateBucketConfiguration( storage_class='IA' ) )) print(vars(result)) ``` -------------------------------- ### DownloadCheckpoint Initialization Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/8-utilities.md Initialize DownloadCheckpoint to manage resumable download state. Specify the destination file path and the directory for checkpoint files. ```python class DownloadCheckpoint: """Manages download checkpoint state for resumable downloads.""" def __init__( self, file_path: str, checkpoint_dir: str, **kwargs ): """ Args: file_path (str): Destination file path. checkpoint_dir (str): Directory for checkpoint files. """ ``` -------------------------------- ### Create Bucket with OSS Python SDK Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/1-client-api.md Use this to create a new OSS bucket. Specify the bucket name, ACL, and storage class configuration. ```python config = oss.CreateBucketConfiguration(storage_class="Standard") result = client.put_bucket(oss.PutBucketRequest( bucket="my-bucket", acl="private", create_bucket_configuration=config )) ``` -------------------------------- ### Handle ParamInvalidError Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/7-exceptions.md Demonstrates how to catch and handle a ParamInvalidError when calling put_object with an invalid parameter. This is useful for validating input before sending requests. ```python try: result = client.put_object(oss.PutObjectRequest( bucket="my-bucket", key="file.txt", body="content" )) except oss.exceptions.ParamInvalidError as e: print(f"Invalid parameter: {e}") ``` -------------------------------- ### Client Configuration with Retry Settings Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/8-utilities.md Demonstrates how to configure the OSS client with retry settings, specifying the maximum number of retry attempts. This configuration is applied when initializing the client. ```python import alibabacloud_oss_v2 as oss config = oss.Config( region="cn-hangzhou", retry_max_attempts=5, # Maximum 5 attempts ) client = oss.Client(config) ``` -------------------------------- ### Get Bucket Statistics with OSS Python SDK Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/1-client-api.md Use this to query statistics about an OSS bucket, including storage size and object count. ```python def get_bucket_stat(self, request: models.GetBucketStatRequest, **kwargs) -> models.GetBucketStatResult: """Queries statistics about a bucket, including storage size and object count.""" ``` -------------------------------- ### OSS Batch Upload Files Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Shows how to upload multiple local files to an OSS bucket using the `put_object_from_file` method in a loop. ```python # Upload many files import os for filename in os.listdir("/local/dir"): filepath = os.path.join("/local/dir", filename) client.put_object_from_file( oss.PutObjectRequest(bucket="my-bucket", key=filename), filepath ) ``` -------------------------------- ### Multipart Upload Management Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Provides examples for managing multipart uploads, including listing in-progress uploads, listing parts of an upload, and aborting an upload. ```APIDOC ## Multipart Upload Management ### Description Manage multipart uploads by listing in-progress uploads, listing parts, and aborting uploads. ### Usage ```python # List in-progress uploads paginator = client.list_multipart_uploads_paginator() for page in paginator.iter_page(oss.ListMultipartUploadsRequest(bucket="my-bucket')): for upload in page.uploads: print(f"{upload.key} (ID: {upload.upload_id})") # List parts of an upload paginator = client.list_parts_paginator() for page in paginator.iter_page(oss.ListPartsRequest( bucket="my-bucket", key="file.zip", upload_id="upload-id" )): for part in page.parts: print(f"Part {part.part_number}: {part.size} bytes") # Abort upload client.abort_multipart_upload(oss.AbortMultipartUploadRequest( bucket="my-bucket", key="file.zip", upload_id="upload-id" )) ``` ``` -------------------------------- ### Configuration Options Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/README.md Details the Config class and all available configuration parameters for initializing and customizing the OSS client, including network settings, credentials, signature, and retry configurations. ```APIDOC ## Configuration ### Description Manages all configuration options for the OSS client, allowing customization of endpoints, credentials, network settings, and more. ### Config Class - **Constructor**: Accepts 33 configuration parameters. - **Parameters**: A comprehensive table detailing each parameter, its type, default value, and description. - **Endpoint and Region**: Configuration for service endpoints and regions. - **Network Settings**: Timeouts, proxy, SSL, redirects. - **Credentials Provider**: Configuration for how credentials are provided. - **Signature and Authentication**: Settings for request signing and authentication. - **Retry Configuration**: Parameters for controlling request retries. - **HTTP Client Settings**: Options for the underlying HTTP client. - **Data Integrity**: Options for data integrity checking. - **Special Features**: CloudBox and other specific feature settings. ### Functions - `load_default()`: Function to load default configuration settings. ### Examples Includes complete configuration examples and specific patterns for proxy configuration. ``` -------------------------------- ### Handle StreamClosedError Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/7-exceptions.md Shows how to handle a StreamClosedError by attempting to read from a response body stream after it has been closed using result.body.close(). This demonstrates proper stream management. ```python result = client.get_object(oss.GetObjectRequest( bucket="my-bucket", key="file.txt" )) result.body.close() # This will raise StreamClosedError try: content = result.body.read() except oss.exceptions.StreamClosedError: print("Stream is closed") ``` -------------------------------- ### Async Operations Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Demonstrates how to perform OSS operations asynchronously using the `AsyncClient` for improved performance in concurrent applications. ```APIDOC ## Async Operations ### Description Perform OSS operations asynchronously using the `AsyncClient`. ### Usage ```python import asyncio from alibabacloud_oss_v2.aio import AsyncClient async def main(): config = oss.config.load_default() config.credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() config.region = "cn-hangzhou" client = AsyncClient(config) result = await client.put_object(oss.PutObjectRequest( bucket="my-bucket", key="file.txt", body=b"content" )) print(f"ETag: {result.etag}") asyncio.run(main()) ``` ``` -------------------------------- ### Handle StreamConsumedError Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/7-exceptions.md Illustrates how to handle a StreamConsumedError by attempting to read from a response body stream after it has already been read once. This highlights the one-time nature of stream reading. ```python import alibabacloud_oss_v2 as oss result = client.get_object(oss.GetObjectRequest( bucket="my-bucket", key="file.txt" )) # First read consumes the stream content = result.body.read() # This will raise StreamConsumedError try: content_again = result.body.read() except oss.exceptions.StreamConsumedError: print("Stream already consumed") ``` -------------------------------- ### Perform Async PUT Object Operation Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/9-quick-reference.md Demonstrates how to perform an asynchronous PUT Object operation using the `AsyncClient`. It loads default configuration and uses environment variables for credentials. ```python import asyncio from alibabacloud_oss_v2.aio import AsyncClient async def main(): config = oss.config.load_default() config.credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() config.region = "cn-hangzhou" client = AsyncClient(config) result = await client.put_object(oss.PutObjectRequest( bucket="my-bucket", key="file.txt", body=b"content" )) print(f"ETag: {result.etag}") asyncio.run(main()) ``` -------------------------------- ### Get Paginator Objects from Client Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/6-paginators.md Instantiate various paginator objects from the OSS client. These paginators are used to retrieve lists of objects, versions, and multipart uploads. ```python import alibabacloud_oss_v2 as oss client = oss.Client(config) # Get paginator objects list_objects_paginator = client.list_objects_paginator() list_objects_v2_paginator = client.list_objects_v2_paginator() list_object_versions_paginator = client.list_object_versions_paginator() list_buckets_paginator = client.list_buckets_paginator() list_parts_paginator = client.list_parts_paginator() list_multipart_uploads_paginator = client.list_multipart_uploads_paginator() ``` -------------------------------- ### Load Default Configuration Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/2-configuration.md This function creates a Config instance with sensible defaults for immediate use. You can then set credentials and region to customize it. ```APIDOC ## Function: load_default() ```python def load_default() -> Config: """Using the SDK's default configuration""" ``` Creates a Config instance with sensible defaults for immediate use. **Returns**: `Config` with: - `signature_version`: "v4" - `connect_timeout`: 10 seconds - `readwrite_timeout`: 20 seconds **Example** ```python import alibabacloud_oss_v2 as oss # Load default configuration config = oss.config.load_default() # Set credentials and region credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() config.credentials_provider = credentials_provider config.region = "cn-hangzhou" # Create client client = oss.Client(config) ``` ``` -------------------------------- ### List Buckets with OSS SDK v2 Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/README.md Lists all buckets in your OSS account using the SDK. Ensure credentials are set as environment variables and the region is specified. ```python import alibabacloud_oss_v2 as oss def main(): region = "cn-hangzhou" # Loading credentials values from the environment variables credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() # Using the SDK's default configuration cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider cfg.region = region client = oss.Client(cfg) # Create the Paginator for the ListBuckets operation paginator = client.list_buckets_paginator() # Iterate through the bucket pages for page in paginator.iter_page(oss.ListBucketsRequest( ) ): for o in page.buckets: print(f'Bucket: {o.name}, {o.location}, {o.creation_date} {o.resource_group_id}') if __name__ == "__main__": main() ``` -------------------------------- ### Retryer Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/3-types.md Abstract base class for retry strategies, defining methods to check if an error is retryable, get the maximum number of attempts, and determine the retry delay. ```APIDOC ## Retryer Abstract base class for retry strategies. ```python class Retryer: """Abstract base class for Retryer.""" @abc.abstractmethod def is_error_retryable(self, error: Exception) -> bool: """Determine if an error is retryable.""" @abc.abstractmethod def max_attempts(self) -> int: """Get the maximum number of attempts.""" @abc.abstractmethod def retry_delay(self, attempt: int, error: Exception) -> float: """Get the delay in seconds before the next retry attempt.""" ``` ``` -------------------------------- ### Handle ParamRequiredError Example Source: https://github.com/aliyun/alibabacloud-oss-python-sdk-v2/blob/master/_autodocs/7-exceptions.md Demonstrates how to catch and handle a ParamRequiredError when a mandatory parameter like 'bucket' is omitted during a put_object call. This helps in debugging missing required fields. ```python try: # Missing required 'bucket' parameter result = client.put_object(oss.PutObjectRequest( key="file.txt", body="content" )) except oss.exceptions.ParamRequiredError as e: print(f"Missing required field: {e}") ```