import base64 import calendar import datetime import hashlib import hmac import os import random from urllib import parse import requests def get_md5_01(file_path): md5 = None if os.path.isfile(file_path): f = open(file_path, 'rb') md5_obj = hashlib.md5() md5_obj.update(f.read()) hash_code = md5_obj.hexdigest() f.close() md5 = str(hash_code).lower() return md5 def createTransaction(HTTPMethod, filePath): fileName = filePath.split('/')[-1] param = { # "Format": "JSON", "Version": '2017-07-11', "AccessKeyId": "LTAIeS8aBuPBZxV2", "SignatureMethod": "HMAC-SHA1", "Timestamp": datetime.datetime.utcnow().isoformat()[:19] + 'Z', "SignatureVersion": "1.0", "SignatureNonce": '9166ab59-f445-' + str(random.randint(1000, 9999)) + '-911d-664c1570df0f', "Action": "CreateTransaction" # "Ext": fileName[-fileName[::-1].index('.'):], # "Md5": get_md5_01(filePath), # "Size": os.path.getsize(filePath) } AccessKeySecret = b'hyPeTaDQBQs6jetYcqY0BUdpacXTH3&' canonicalQueryString = '' for i in sorted(param.items(), key=lambda d: d[0]): canonicalQueryString += '&' + i[0] + '=' + str(i[1]) print(canonicalQueryString[1:]) strUrlEncoding = HTTPMethod + '&%2F&' + parse.quote(canonicalQueryString[1:]) print(strUrlEncoding) stringToSign = base64.b64encode(hmac.new(AccessKeySecret, strUrlEncoding.encode('UTF-8'), 'sha1').digest()) print(stringToSign) server = 'https://cloudphoto.cn-shanghai.aliyuncs.com' url = server + "?" + canonicalQueryString[1:] + '&Signature=' + parse.quote(stringToSign.decode('utf-8')).replace( '/', '%2F') print(url) result = requests.get(url) print(result.content) if __name__ == '__main__': createTransaction("GET", "C:/Users/10295/Desktop/灵梦.png") # print(datetime.datetime.utcnow())