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

Post 表单预签名(Python SDK)

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

首次发布时间2023.01.19 17:25:20

本文介绍 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("Data:", 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 表单预签名的详细信息,请参见基于浏览器上传的表单中包含签名