Tencent Cloud Object Storage (COS) SDK for Python v5

1.9.41 · active · verified Mon Apr 13

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the COS client and list existing buckets. It retrieves credentials from environment variables (recommended for security) and includes basic error handling.

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}")

view raw JSON →