本文介绍 POST 表单预签名的示例代码。
以下代码用于使用 POST 表单预签名向桶 bucket-test
添加对象 object-test
。
import os import tos from tos.models2 import PostSignatureCondition # 从环境变量获取 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-test" try: client = tos.TosClientV2(ak, sk, endpoint, region) # 签名 out = client.pre_signed_post_signature(bucket=bucket_name, key=object_key, # 可通过可选参数conditions添加其余信息 conditions=[PostSignatureCondition(key='x-tos-acl', value='private')]) print("Algorithm:", out.algorithm) print("Date:", out.date) print("Policy:", out.policy) print("Signature:", out.signature) print("Credential:", out.credential) print("OriginPolicy:", out.origin_policy) 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))
关于 POST 表单预签名的详细信息,请参见基于浏览器上传的表单中包含签名。