59 lines
1.8 KiB
Python
59 lines
1.8 KiB
Python
# -*- coding: utf-8 -*-
|
|
# @Time: 2024/5/30 13:22
|
|
|
|
import uuid
|
|
import hmac
|
|
import time
|
|
import urllib
|
|
import sys
|
|
import base64
|
|
from hashlib import sha1
|
|
|
|
AK = 'ee5099861e2311efb7477e4382034994'
|
|
AccessKeySecret = '4f48e911c7dfdd9c66842e2d7146e387'
|
|
|
|
def percentEncode(str):
|
|
"""将特殊转义字符替换"""
|
|
res = urllib.parse.quote(str.encode('utf-8').decode(sys.stdin.encoding).encode('utf8'), '')
|
|
res = res.replace('+', '%20')
|
|
res = res.replace('*', '%2A')
|
|
res = res.replace('%7E', '~')
|
|
return res
|
|
|
|
|
|
def get_signature(action, method, url, param={}):
|
|
"""
|
|
@params: action: 接口动作
|
|
@params: ak: ak值
|
|
@params: access_key_secret: ak秘钥
|
|
@params: method: 接口调用方法(POST/GET)
|
|
@params: param: 接口调用Query中参数(非POST方法Body中参数)
|
|
@params: url: 接口调用路径
|
|
@return: 请求的url可直接调用
|
|
"""
|
|
ak = AK
|
|
access_key_secret = AccessKeySecret
|
|
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
|
D = {
|
|
'Action': action,
|
|
'AccessKeyId': ak,
|
|
'SignatureMethod': 'HMAC-SHA1',
|
|
'SignatureNonce': str(uuid.uuid1()),
|
|
'SignatureVersion': "1.0",
|
|
"Timestamp": timestamp,
|
|
'Version': '2019-08-08',
|
|
}
|
|
if param:
|
|
D.update(param)
|
|
sortedD = sorted(D.items(), key=lambda x: x[0])
|
|
canstring = ''
|
|
for k, v in sortedD:
|
|
canstring += '&' + percentEncode(k) + '=' + percentEncode(v)
|
|
stringToSign = method + '&%2F&' + percentEncode(canstring[1:])
|
|
key_bytes = bytes(access_key_secret, 'utf-8') # Commonly 'latin-1' or 'utf-8'
|
|
data_bytes = bytes(stringToSign, 'utf-8') # Assumes `data` is also a string.
|
|
h = hmac.new(key_bytes, data_bytes, sha1)
|
|
Signature = base64.encodebytes(h.digest()).strip()
|
|
D['Signature'] = Signature
|
|
url = url + '/?' + urllib.parse.urlencode(D)
|
|
return url |