You need to enable JavaScript to run this app.
导航
设置对象级过期时间(Python SDK)
最近更新时间:2025.09.02 16:41:28首次发布时间:2025.09.02 16:41:28
复制全文
我的收藏
有用
有用
无用
无用

您可以通过 TOS Python SDK 的 set_object_expires 接口设置已上传对象的过期时间,过期后,TOS 将自动删除该对象。

注意事项

  • 设置对象级过期时间,您必须具备 tos:SetObjectExpires 权限,具体操作,请参见权限配置指南
  • 使用 Python SDK 设置对象级过期时间,要求 Python SDK 为 2.8.5 或以上版本。

示例代码

import os
import tos

# 从环境变量获取 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"
# 对象名称,例如 example_dir 下的 example_object.txt 文件,则填写为 example_dir/example_object.txt
object_key = "object-test"
try:
    # 创建 TosClientV2 对象,对桶和对象的操作都通过 TosClientV2 实现
    client = tos.TosClientV2(ak, sk, endpoint, region)
    # 设置对象级过期时间,取值为正整数或0;为0时表示永不过期。
    object_expires = 1
    client.set_object_expires(bucket_name, object_key, object_expires)
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))

相关文档

关于设置对象级过期时间的 API 文档,请参见 SetObjectExpires