# -*- 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}.myqcloud.com/{Key}'
if __name__ == '__main__':
bucket = 'xxxx' # 雲儲存桶名稱,最好根據項目來方便後續管理
LocalFilePath = 'test.jpeg' # //代指本地文件路徑
Key = 'test.jpeg' # //上傳到桶之後的文件名
print(cos_upload_file(bucket, LocalFilePath, Key))
騰訊雲cos上傳文件模板
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.