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

判断对象是否存在(Python SDK)

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

首次发布时间2023.11.28 11:52:59

您可以通过 Python SDK 的 head_object 接口判断对象是否存在。

注意事项

要判断对象是否存在,您的账号必须具备 tos:GetObject 权限,具体操作请参见权限配置指南

示例代码

以下代码展示如何判断对象是否存在。

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'
object_key = 'object-key'
try:
    # 创建 TosClientV2 对象,对桶和对象的操作都通过 TosClientV2 实现
    client = tos.TosClientV2(ak, sk, endpoint, region)
    # 获取对象元数据
    result = client.head_object(bucket_name, object_key)
except tos.exceptions.TosClientError as e:
    # 操作失败,捕获客户端异常,一般情况为非法请求参数或网络异常
    print('fail with client error, message:{}, cause: {}'.format(e.message, e.cause))
except tos.exceptions.TosServerError as e:
    if e.status_code == 404:
        print("Object not found.")
    else:
        # 操作失败,捕获服务端异常,可从返回信息中获取详细错误信息
        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 接口,请参见 HeadObject