# -*- coding: utf-8 -*-
import base64
import datetime
import hmac
import json
import time
from hashlib import sha1 as sha
def get_iso_8601(expire, utc=8):
gmt = datetime.datetime.utcfromtimestamp(expire + utc * 60 * 60).isoformat()
gmt += "Z"
return gmt
access_key_id = "your access_key_id "
access_key_secret = "your access_key_secret "
# 填写Bucket名称。
bucket_name = '填写Bucket名称'
def get_token():
save_name = '文件名称'
upload_dir = "upload"
expire_time = int(time.time()) + 600
policy_dict = {
"conditions": [
# ["eq", "$bucket", "md-hz"],
# ["starts-with", "$key", upload_dir]
# 10G = 10 * 1024 * 1024 * 1024 = 10737418240
# ["content-length-range", 5, 10737418240]
["content-length-range", 1, 10737418240]
],
"expiration": get_iso_8601(expire_time)
}
policy = json.dumps(policy_dict).strip()
policy_encode = base64.b64encode(policy.encode("utf-8"))
h = hmac.new(access_key_secret.encode("utf-8"), policy_encode, sha)
sign_result = base64.encodebytes(h.digest()).strip()
token_dict: dict = {
"OSSAccessKeyId": access_key_id,
"policy": policy_encode.decode('utf-8'),
"signature": sign_result.decode('utf-8'),
"expire": str(expire_time),
"key": f'{upload_dir}/{save_name}'
}
return token_dict