Python签名演示

最近更新时间: 2022-10-27 10:30:02

注意:如果是在 Python 2 环境中运行,需要先安装 requests 依赖包: pip install requests 。 # -- coding: utf-8 -- import base64
import hashlib
import hmac
import time

import requests

secret_id = "AKIDmDJ4SUPSOW4R8**" secret_key = "G9Gavsd8F9RfJ5JWf3**"

def get_string_to_sign(method, endpoint, params):
s = method + endpoint + "/?"
query_str = "&".join("%s=%s" % (k, params[k]) for k in sorted(params))
return s + query_str

def sign_str(key, s, method):
hmac_str = hmac.new(key.encode("utf8"), s.encode("utf8"), method).digest()
return base64.b64encode(hmac_str)

if name == 'main':
endpoint = "contentsecurity.api3.yun.ccb.com"
data = {
'Action' : 'BspTextRecognition',
'Nonce' : 11886,
'MessageContent' : "测试信息",
'Region' : 'wh', 'SecretId' : secret_id,
'Timestamp' : int(time.time()), # int(time.time())
'Version': '2019-03-05'
} s = get_string_to_sign("GET", endpoint, data)
data["Signature"] = sign_str(secret_key, s, hashlib.sha1)
print(data["Signature"])
# 此处会实际调用,成功后可能产生计费
resp = requests.get("https://" + endpoint, params=data)
print(resp.url)