代码语言:javascript复制
# -*- coding=utf-8
# appid 已在配置中移除,请在参数 Bucket 中带上 appid。Bucket 由 BucketName-APPID 组成
# 1. 设置用户配置, 包括 secretId,secretKey 以及 Region
# python3 安装
# 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' # 替换为用户的 secretId
secret_key = 'xxxxxxx' # 替换为用户的 secretKey
region = 'ap-shanghai' # 桶的Location 可以client.list_buckets 查看获取
APPID = "xxxxxx" # APPID
bucket_name = "xxxx" # 桶名的前缀
bucket = f'{bucket_name}-{APPID}' # 桶名的前缀-APPID
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
# 2. 获取客户端对象
client = CosS3Client(config)
def cos_list_buckets():
'''查看当前用户下的桶的列表'''
response = client.list_buckets(
)
print(response)
def cos_bucket_status(Bucket):
'''
验证权限
:param Bucket:桶名
:return: True 有权限,None没有权限
'''
try:
response = client.head_bucket(
Bucket=Bucket,
)
if not response:
return True
except:
return None
def cos_upload_file(Bucket, LocalFilePath, Key):
'''
上传文件
:param Bucket: 桶名
:param LocalFilePath: 本地文件路径
:param Key: 传到桶之后的文件名
:return:
'''
response = client.upload_file(
Bucket='xxxxxx', # 云储存桶名称,最好根据项目来方便后续管理 格式前缀-APPID
LocalFilePath=LocalFilePath, # //代指本地文件路径
Key=Key, # //上传到桶之后的文件名
)
ETag = response["ETag"]
return f'https://{Bucket}.cos.{region}.myzijiebao.com/{Key}'
if __name__ == '__main__':
bucket = 'xxxx' # 云储存桶名称,最好根据项目来方便后续管理
LocalFilePath = 'test.jpeg' # //代指本地文件路径
Key = 'test.jpeg' # //上传到桶之后的文件名
print(cos_upload_file(bucket, LocalFilePath, Key))