strToSign的构造过程以如下流程简要说明:
product.json文件内容
{
"vod":{
"Format":"JSON",
"Version":"2017-03-21",
"AccessKeyId":"yourAccessKeyID",
"SignatureMethod":"HMAC-SHA1",
"SignatureVersion":"1.0"
}
}
代码正文:
# coding=utf-8
import json
import uuid
import datetime
import hmac
import base64
from urllib import quote
import hashlib
class SignatureUrl():
"""python 计算openapi的签名"""
def __init__(self, public_param, private_param):
self.public_param = public_param
self.private_param = private_param
def get_timestamp(self):
time_format = "%Y-%m-%dT%H:%M:%SZ"
return datetime.datetime.utcnow().strftime(time_format)
def get_uuid(self):
return str(uuid.uuid1())
def url_encode_str(self, all_params):
sort_all_params = list()
for key, value in all_params.items():
params = key + '=' + value
sort_all_params.append(params)
# 对参数进行升序排序
sort_all_params.sort()
for i in range(len(sort_all_params)):
# 对参数以及参数值进行urlencode处理,注意:’=‘此时不能处理,否则后面会再次对%3D进行encode
sort_all_params[i] = quote(sort_all_params[i], '=')
# 对encode之后的字符串进行再处理
tmp = sort_all_params[i]
if tmp.find('+'):
tmp.replace('+','%20')
elif tmp.find('*'):
tmp.replace('*','%2A')
elif tmp.find('%7E'):
tmp.replace('%7E','~')
sort_all_params[i] = tmp
return sort_all_params
def get_signature(self, param, http_method,AccesskeySecret):
str_to_sign = ''
sort_all_params = self.url_encode_str(param)
print(sort_all_params)
for i in range(len(sort_all_params)):
str_to_sign = str_to_sign + sort_all_params[i] + '&'
# 将最后一位&给截取掉
str_to_sign = http_method + '&%2F&' + quote(str_to_sign[:-1])
print(str_to_sign)
key = AccesskeySecret+'&'
signature = hmac.new(key.encode(
'utf-8'), str_to_sign.encode('utf-8'), digestmod=hashlib.sha1)
signature = base64.b64encode(signature.digest())
# 解决签名中包含有'+'的特殊情况
signature = list(signature)
for i in range(len(signature)):
if signature[i] == '+':
signature[i] = '%2B'
newSignature = ''.join(signature)
self.private_param['Signature'] = newSignature
def url_factory(self):
all_params = dict(self.public_param, **self.private_param)
self.get_signature(all_params, 'GET','yourAccessKeySecret')
url = 'http://vod.cn-shanghai.aliyuncs.com' + '?AccessKeyId=' + self.public_param['AccessKeyId'] + '&Action=' + self.private_param['Action'] + '&Format=' + self.public_param['Format'] + '&Version=' + self.public_param['Version'] + '&SignatureMethod=' + self.public_param['SignatureMethod'] + \
'&SignatureVersion=' + self.public_param['SignatureVersion'] + '&Timestamp=' + self.public_param['Timestamp'] + '&SignatureNonce=' + \
self.public_param['SignatureNonce'] + '&VideoId=' + \
self.private_param['VideoId'] + '&Signature=' + self.private_param['Signature']
print('url is : ' + url)
public_param = dict()
private_param = dict()
pubduct = 'vod'
with open("/Users/storageuser/PycharmProjects/openapiPython/product.json", "r") as param:
files = json.load(param)
#public_param["Endpoint"] = files[pubduct]["Endpoint"].encode("utf-8")
public_param["Format"] = files[pubduct]["Format"].encode("utf-8")
public_param["Version"] = files[pubduct]["Version"].encode("utf-8")
public_param["AccessKeyId"] = files[pubduct]["AccessKeyId"].encode("utf-8")
public_param["SignatureMethod"] = files[pubduct]["SignatureMethod"].encode("utf-8")
public_param["SignatureVersion"] = files[pubduct]["SignatureVersion"].encode("utf-8")
action_param = dict()
action_param["VideoId"] = "f6a21eade82f4cf6b45669fa34b35b76"
action_param["Action"] = "GetVideoPlayAuth"
private_param["Action"] = action_param["Action"]
private_param["VideoId"] = action_param["VideoId"]
sig = SignatureUrl(public_param, private_param)
sig.public_param["Timestamp"] = sig.get_timestamp()
sig.public_param["SignatureNonce"] = sig.get_uuid()
sig.url_factory()