Python-七牛云token生成器

Python Easy!

Posted by MetaNetworks on February 27, 2020
本页面总访问量

Python生成带有时限的上传token

根据博文的教程,使用Python语言实现了一遍

token = accessKey + encodedSign + encoded

需要准备的数据:

  • AccessKey
  • SecretKey
  • OSS Bucket名称
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import base64
import hmac
import json
import time
from hashlib import sha1

# access_key
access_key = "你的AccessKey"
# secret_key
secret_key = "你的SecretKey"
# bucket
bucket = "你的bucket仓库名称"
# token过期(s)
expired_time = 3600


# 获取Token
def get_token():
    data = {"scope": bucket}
    exp_time = int(time.time()) + expired_time
    data["deadline"] = exp_time
    s = json.JSONEncoder().encode(data).encode("utf-8")
    encoded = base64.b64encode(s)
    encoded_sign = base64.b64encode(hmac.new(secret_key.encode("utf-8"), encoded, sha1).digest()).decode("utf-8")
    return access_key + ":" + encoded_sign + ":" + encoded.decode("utf-8")


# 主函数
if __name__ == '__main__':
    print(get_token())

[2020.02.08] 记录:亲测可用,可用正常上传