You need to enable JavaScript to run this app.
文档中心
对象存储

对象存储

复制全文
下载 pdf
典型场景介绍
移动及重命名场景(Python SDK)
复制全文
下载 pdf
移动及重命名场景(Python SDK)

如果您需要在 Bucket 中对文件进行重命名,您可以通过 CopyObject 接口将源对象拷贝至目标对象,然后通过 DeleteObject 接口删除源对象。

重命名单个对象

以下代码用于将桶 bucket-test 中对象 src-object 重命名为 dest-object

import os
import tos

# 从环境变量获取 AK 和 SK 信息。
ak = os.getenv('TOS_ACCESS_KEY')
sk = os.getenv('TOS_SECRET_KEY')
endpoint = "your endpoint"
region = "your region"
bucket_name = "bucket-test"
try:
    client = tos.TosClientV2(ak, sk, endpoint, region)

    resp = client.copy_object('bucket-test', 'dest-object', 'bucket-test', 'src-object')
    # 查看返回状态,若为200,则表示执行成功。
    print('result status', resp.status_code)
    resp = client.delete_object('bucket-test', 'src-object')
    # 查看返回状态,若为200,则表示执行成功。
    print('result status', resp.status_code)
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))

重命名目录

以下代码用于将桶 bucket-test 中目录 exampledir1/ 重命名为 exampledir2/

import os
import tos

# 从环境变量获取 AK 和 SK 信息。
ak = os.getenv('TOS_ACCESS_KEY')
sk = os.getenv('TOS_SECRET_KEY')
endpoint = "your endpoint"
region = "your region"
bucket_name = 'bucket-test'
dir_1 = 'exampledir1/'
dir_2 = 'exampledir2/'

client = tos.TosClientV2(ak, sk, endpoint, region)

truncated = True
continuation_token = ''
while truncated:
    result = client.list_objects_type2(bucket_name, continuation_token=continuation_token, prefix=dir_1)
    for iterm in result.contents:
        new_key = iterm.key
        if iterm.key == dir_1:
            new_key = dir_2
        else:
            new_key = dir_2 + new_key.removeprefix(dir_1)
        client.copy_object(bucket_name, new_key, bucket_name, iterm.key)
        client.delete_object(bucket_name, iterm.key)
    truncated = result.is_truncated
    continuation_token = result.next_continuation_token

相关文档

  • 关于拷贝对象 API 文档,请参见 CopyObject
  • 关于删除对象 API 文档,请参见 DeleteObject
最近更新时间:2024.04.26 17:28:04
这个页面对您有帮助吗?
有用
有用
无用
无用