import base64 import hmac import hashlib import json import time import requests def urlsafe_base64_encode(data): if isinstance(data, str): data = data.encode('utf-8') ret = base64.urlsafe_b64encode(data) # base64url standard replaces padding '=' with nothing return ret.decode('utf-8').rstrip('=') def generate_token(ak, sk, bucket, key, scope_key=True): deadline = int(time.time()) + 3600 scope = f"{bucket}:{key}" if scope_key else bucket policy = { "scope": scope, "deadline": deadline } policy_str = json.dumps(policy, separators=(',', ':')) encoded_policy = urlsafe_base64_encode(policy_str) # hmac-sha1 hashed = hmac.new(sk.encode('utf-8'), encoded_policy.encode('utf-8'), hashlib.sha1) encoded_signature = urlsafe_base64_encode(hashed.digest()) return f"{ak}:{encoded_signature}:{encoded_policy}" ak = "vf63aPF-QIFbyzULtHaSx9JgiVSS3zRuy0zmBACE" sk = "JlQvHevHSAgilNYaH0UxQoX68rb4m9VflpaXtYL1" bucket = "fmqi-img" key = "astroresearch/test_hello.txt" token = generate_token(ak, sk, bucket, key, scope_key=True) print(f"Generated python token: {token}") # Let's try uploading files = {'file': ('test.txt', b'hello python')} data = {'token': token, 'key': key} res = requests.post("https://up-z1.qiniup.com", data=data, files=files) print(f"Python upload status: {res.status_code}") print(f"Python upload response: {res.text}")