腾讯对象存储

389 阅读2分钟

python实现上传文件

pip install -U cos-python-sdk-v5

# -*- coding=utf-8
# appid 已在配置中移除,请在参数 Bucket 中带上 appid。Bucket 由 BucketName-APPID 组成
# 1\. 设置用户配置, 包括 secretId,secretKey 以及 Region
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys

secret_id = 'COS_SECRETID'      # 替换为用户的 secretId
secret_key = 'COS_SECRETKEY'      # 替换为用户的 secretKey
region = 'ap-beijing.'     # 替换为用户的 Region

token = None                # 使用临时密钥需要传入 Token,默认为空,可不填
scheme = 'https'            # 指定使用 http/https 协议来访问 COS,默认为 https,可不填
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
# 2\. 获取客户端对象
client = CosS3Client(config)

# 创建桶
response = client.create_bucket(
    Bucket='examplebucket-1250000000'
)

# 上传文件

response = client.upload_file(
    Bucket='gyf-1300000000',   # 创建桶的名称
    LocalFilePath='local.txt',  # 本地文件路径
    Key='picture.jpg',			# 上传到桶之后的文件名
    PartSize=1,
    MAXThread=10,
    EnableMD5=False
)
print(response['ETag'])

上传文件示例代码

from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client

secret_id = '自己的id'      # 替换为用户的 secretId
secret_key = '自己的key'      # 替换为用户的 secretKey
region = 'ap-beijing'     # 替换为用户的 Region

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, )
# 2\. 获取客户端对象
client = CosS3Client(config)

response = client.upload_file(
    Bucket='gyf-1301115254',   # 创建桶的名称
    LocalFilePath='code.png',  # 本地文件路径
    Key='p1.png',			# 上传到桶之后的文件名

)
print(response['ETag'])

创建桶示例代码

from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client

secret_id = '自己的id'  # 替换为用户的 secretId
secret_key = '自己的key'  # 替换为用户的 secretKey
region = 'ap-beijing'  # 替换为用户的 Region

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, )
# 2\. 获取客户端对象
client = CosS3Client(config)

response = client.create_bucket(
    Bucket='test-1300000000',  # 创建桶的名称
    ACL="public-read",  # private  / public-read / public-read-write
)

项目中集成cos

创建项目时创建桶
name = form.cleaned_data['name']
# 为项目创建一个桶

bucket = "{}-{}-{}-1300000000".format(name,request.tracer.user.mobile_phone,str(int(time.time())))
        region = "ap-beijing"
        create_bucket(bucket,region)

# utils/tencent/cos.py

from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from django.conf import settings

def create_bucket(bucket ,region= 'ap-beijing'):
    """
    创建桶
    :param bucket: 桶名称
    :param region: 区域
    :return:
    """

    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY, )
    # 2\. 获取客户端对象
    client = CosS3Client(config)

    client.create_bucket(
        Bucket=bucket,  # 创建桶的名称
        ACL="public-read",  # private  / public-read / public-read-write
    )