DEV Community

kunzhu0710
kunzhu0710

Posted on

Tencent cloud cos upload file template

# -*- coding=utf-8
# 1. set config, 包括 secretId,secretKey 以及 Region
# python3 install
# pip3 install qcloud_cos_py3
# pip3 install cos-python-sdk-v5
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys

secret_id = 'xxxxxx'  
secret_key = 'xxxxxxx'  
region = 'ap-shanghai'  
APPID = "xxxxxx"  # APPID
bucket_name = "xxxx"  
bucket = f'{bucket_name}-{APPID}' 
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
# 2. get client object
client = CosS3Client(config)


def cos_list_buckets():

    response = client.list_buckets(
    )
    print(response)


def cos_bucket_status(Bucket):

    try:
        response = client.head_bucket(
            Bucket=Bucket,
        )
        if not response:
            return True
    except:
        return None


def cos_upload_file(Bucket, LocalFilePath, Key):

    response = client.upload_file(
        Bucket='xxxxxx',  
        LocalFilePath=LocalFilePath,  
        Key=Key,  
    )
    ETag = response["ETag"]
    return f'https://{Bucket}.cos.{region}.myqcloud.com/{Key}'


if __name__ == '__main__':
    bucket = 'xxxx'
    LocalFilePath = 'test.jpeg'  
    Key = 'test.jpeg' 

    print(cos_upload_file(bucket, LocalFilePath, Key))
Enter fullscreen mode Exit fullscreen mode

tencent cloud cos

Top comments (0)