Tencent cloud COS实践.md

概述:Tencent cloud COS存储实践.md

对象存储 Cloud object Store/COS

install

1
pip install -U cos-python-sdk-v5

config

1
2
3
4
5
6
7
8
9
10
11
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
secret_id = 'AKIDEI7fz3fzY0DUTCwz1nHUGn5sOKzNkP9c' # 替换为用户的 secretId
secret_key = 'Lq2VkmY3gBOL1lUrypgdCWZYkTxBHgbG' # 替换为用户的 secretKey
region = 'ap-guangzhou' # 替换为用户的 Region
token = None # 使用临时密钥需要传入 Token,默认为空,可不填
scheme = 'https' # 指定使用 http/https 协议来访问 COS,默认为 https,可不填
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token)

获取客户端对象

1
client = CosS3Client(config)

创建存储桶

1
2
3
response = client.create_bucket(
Bucket='examplebucket-1250000000'
)

查看存储桶列表

1
response = client.list_buckets()

查看存储桶文件

1
2
3
4
response = client.list_objects(
Bucket='pic-1302652079',
Prefix='person'
)

文件上传

1
2
3
4
5
6
7
8
9
10
file_name = '通过制品名查询发布单.py'
with open('通过制品名查询发布单.py', 'rb') as fp:
response = client.put_object(
Bucket='pic-1302652079', # Bucket由bucketname-appid组成
Body=fp,
Key=file_name,
StorageClass='STANDARD',
ContentType='text/html; charset=utf-8'
)
print(response['ETag'])

文件下载

1
2
3
4
5
response = client.get_object(
Bucket='pic-1302652079',
Key='通过制品名查询发布单.py',
)
response['Body'].get_stream_to_file('转义.py')

文件删除

1
2
3
4
response = client.delete_object(
Bucket='pic-1302652079',
Key='通过制品名查询发布单.py'
)