You need to enable JavaScript to run this app.
导航

分片拷贝(Python SDK)

最近更新时间2024.02.04 18:31:03

首次发布时间2023.01.19 18:21:16

对象大于 5GiB 时,您可以使用分片拷贝。

注意事项

  • 拷贝文件不支持跨区域的桶间拷贝。
  • 拷贝对象时,账号必须具备源对象的读取权限和目标桶的写入权限。
  • 拷贝对象时,可以保留所有元数据(默认值)或指定新的元数据。但 ACL 并未被保留,而是设置为私有。

分片拷贝步骤

对象大于 5GiB 时,需要使用 upload_part_copy 来进行分片拷贝,包括三个步骤:

  1. 通过 create_multipart_upload 初始化分片拷贝任务。
  2. 通过 upload_part_copy 进行分片拷贝。
  3. 通过 complete_multipart_upload 合并分片。

示例代码

以下代码用于拷贝 src_bucket_name 桶中 src_object_key 对象到 bucket_name 桶中,并设置对象名为 object_key

import os
import tos
from tos.models2 import UploadedPart

# 从环境变量获取 AK 和 SK 信息。
ak = os.getenv('TOS_ACCESS_KEY')
sk = os.getenv('TOS_SECRET_KEY')
# your endpoint 和 your region 填写Bucket 所在区域对应的Endpoint。# 以华北2(北京)为例,your endpoint 填写 tos-cn-beijing.volces.com,your region 填写 cn-beijing。
endpoint = "your endpoint"
region = "your region"
bucket_name = "bucket-test"
object_key = "object-test"
src_bucket_name = "your src bucket name"
src_object_key = "your src object key"
try:
    # 创建 TosClientV2 对象,对桶和对象的操作都通过 TosClientV2 实现
    client = tos.TosClientV2(ak, sk, endpoint, region)

    # 获取 桶 src_bucket 中已存在对象 src_object 的大小
    head_info = client.head_object(src_bucket_name, src_object_key)
    total_size = head_info.content_length
    part_size = 1024 * 1024 * 5
    # 初始化一个 Multipart 任务
    resp = client.create_multipart_upload(bucket_name, object_key)
    upload_id = resp.upload_id

    # 拷贝分片
    parts = []
    part_number = 1
    offset = 0
    while offset < total_size:
        num_to_upload = min(part_size, total_size - offset)
        end = offset + num_to_upload - 1

        result = client.upload_part_copy(bucket_name, object_key, upload_id, part_number, src_bucket_name,
                                         src_object_key,
                                         copy_source_range_start=offset, copy_source_range_end=end)

        parts.append(UploadedPart(part_number, result.etag))
        offset += num_to_upload
        part_number += 1
    # 完成分片拷贝。
    resp = client.complete_multipart_upload(bucket_name, object_key, upload_id, parts=parts)
except tos.exceptions.TosClientError as e:
    # 操作失败,捕获客户端异常,一般情况为非法请求参数或网络异常
    print('fail with client error, message:{}, cause: {}'.format(e.message, e.cause))
except tos.exceptions.TosServerError as e:
    # 操作失败,捕获服务端异常,可从返回信息中获取详细错误信息
    print('fail with server error, code: {}'.format(e.code))
    # request id 可定位具体问题,强烈建议日志中保存
    print('error with request id: {}'.format(e.request_id))
    print('error with message: {}'.format(e.message))
    print('error with http code: {}'.format(e.status_code))
    print('error with ec: {}'.format(e.ec))
    print('error with request url: {}'.format(e.request_url))
except Exception as e:
    print('fail with unknown error: {}'.format(e))

相关文档