一、背景

客户反馈随机上传小文件至cos速度比较慢,用Python来进行测试上传速度。

二、代码

#!/bin/env python
# -*- coding:utf-8 -*-
# _auth:kaliarch
# use cos-python-sdk-v5
# https://cloud.tencent.com/document/product/436/12269

from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import random
import string
import datetime

secret_id = 'AKIDMdjegcmoGYiolXxxxxxxxxxxxxxxxdE'      # 替换为用户的 secretId
secret_key = 'd5MRL4VoxyxxxxxxxxxxxA2lNq7D'      # 替换为用户的 secretKey
region = 'ap-chengdu'     # 替换为用户的 Region                 # 使用临时密钥需要传入 Token,默认为空,可不填
scheme = 'https'            # 指定使用 http/https 协议来访问 COS,默认为 https,可不填
bucket_name = 'xuel-test-bucket-1253961596'        #制定bucket地址
config = CosConfig(Region=region, Secret_id=secret_id, Secret_key=secret_key,  Scheme=scheme)
# 2. 获取客户端对象
client = CosS3Client(config)

def get_data_list(number):
    """
    获取随机字符串,number指定数量
    :param number:
    :return:
    """
    for i in range(int(number)):
        random_str = ''.join(random.sample(string.ascii_letters + string.digits, 12))
        yield str(i) + random_str

def get_func_time(func):
    """
    装饰器函数
    :param func: 计算内层函数执行时间
    :return:
    """
    def inter_func(*args):
        stime = datetime.datetime.now()
        print('start datetime:', stime)
        func(*args)
        etime = datetime.datetime.now()
        print('start datetime:', etime)
        print('duration time', etime - stime)
    return inter_func

@get_func_time
def upload_cos(number=1000):
    """
    cos 文件上传
    :param number:
    :return:
    """
    print('data file number:',str(number))
    for content in get_data_list(number):
        response = client.put_object(
            Bucket=bucket_name,
            Body=bytes(content,encoding='utf-8'),
            Key=content,
        )

if __name__ == '__main__':
    upload_cos(1000)

三、测试

测试500个随机文件
简单COS文件上传测试_第1张图片
测试1000个随机文件
简单COS文件上传测试_第2张图片
查看cos文件数据
简单COS文件上传测试_第3张图片