桶(Bucket)是 TOS 的全局唯一的命名空间,相当于数据的容器,用来储存对象(Object)数据。本文介绍如何获取桶元数据,和判断桶是否存在。
tos:HeadBucket
权限。具体操作,请参见权限配置指南。以下代码用于获取桶 bucket-test 元数据。
import http 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) head_bucket_out = client.head_bucket(bucket_name) print('region: ', head_bucket_out.region) print('storageClass: ', head_bucket_out.storage_class) print('azRedundancy: ', head_bucket_out.az_redundancy) 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 == http.HTTPStatus.NOT_FOUND: # http状态码为 404, 说明桶不存在 print('bucket not exist') elif e.status_code == http.HTTPStatus.FORBIDDEN: # http状态码为 403, 说明不具备HeadBucket权限 print('do not have head bucket policy') 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 文档,请参见 HeadBucket。