Tencent Cloud Object Storage (COS) SDK for Python v5
The `cos-python-sdk-v5` is the official Tencent Cloud COS Python SDK. It provides an interface for interacting with Tencent Cloud Object Storage service, supporting a wide range of operations like bucket and object management. The library currently supports Python 2.6, 2.7, and Python 3.x. It is actively maintained with regular updates.
Warnings
- breaking The older `cos-python-sdk` (without '-v5') is deprecated and uses an outdated JSON API. Users must upgrade to `cos-python-sdk-v5`, which uses the XML API.
- gotcha The `Appid` parameter has been removed from `CosConfig`. The Appid should now be appended to the `Bucket` name when making calls (e.g., `examplebucket-1250000000`).
- gotcha Avoid creating a new `CosS3Client` instance for each operation. It is recommended to create only one instance per region and reuse it for multiple operations (e.g., looping uploads/downloads) to prevent excessive connections and threads.
- gotcha For security, it is highly recommended to use sub-account keys and environment variables to call the SDK, following the principle of least privilege. If permanent secret keys are used, restrict their permissions to the minimum necessary.
Install
-
pip install -U cos-python-sdk-v5
Imports
- CosConfig
from qcloud_cos import CosConfig
- CosS3Client
from qcloud_cos import CosS3Client
- CosServiceError
from qcloud_cos import CosServiceError
- CosClientError
from qcloud_cos import CosClientError
Quickstart
import os
import logging
from qcloud_cos import CosConfig, CosS3Client, CosServiceError
logging.basicConfig(level=logging.INFO, stream=os.sys.stdout)
secret_id = os.environ.get('TENCENTCLOUD_SECRET_ID', '')
secret_key = os.environ.get('TENCENTCLOUD_SECRET_KEY', '')
region = os.environ.get('TENCENTCLOUD_REGION', 'ap-beijing') # Example region
token = None # Use None for permanent keys, provide if using temporary keys
if not secret_id or not secret_key:
print("Please set TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY environment variables.")
else:
try:
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token)
client = CosS3Client(config)
# Example: List buckets
response = client.list_buckets()
print("Successfully listed buckets:")
for bucket_info in response.get('Buckets', []):
print(f" Bucket Name: {bucket_info.get('Name')}, Creation Date: {bucket_info.get('CreationDate')}")
except CosServiceError as e:
print(f"COS Service Error: {e.get_status_code()} - {e.get_error_code()} - {e.get_error_msg()}")
except CosClientError as e:
print(f"COS Client Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")