参考代码:
代码语言:javascript复制#!/usr/bin/env python
# -*- coding: utf-8 -*-
import hmac,time,urllib,hashlib,requests
from urllib import quote
from urlparse import urlparse
from requests.auth import AuthBase
def to_string(data):
"""转换unicode为string.
:param data(unicode|string): 待转换的unicode|string.
:return(string): 转换后的string.
"""
if isinstance(data, unicode):
return data.encode('utf8')
return data
class CosS3Auth(AuthBase):
def __init__(self, secret_id, secret_key, key='', params={}, expire=10000):
self._secret_id = to_string(secret_id)
self._secret_key = to_string(secret_key)
self._expire = expire
self._params = params
if key:
if key[0] == '/':
self._path = key
else:
self._path = '/' key
else:
self._path = '/'
def __call__(self, r):
path = self._path
uri_params = {}
headers = {}
# reserved keywords in headers urlencode are -_.~, notice that / should be encoded and space should not be encoded to plus sign( )
headers = dict([(k.lower(), quote(v, '-_.~')) for k, v in headers.items()]) # headers中的key转换为小写,value进行encode
format_str = "{method}n{host}n{params}n{headers}n".format(
method=r.method.lower(),
host=path,
params=urllib.urlencode(sorted(uri_params.items())),
headers='&'.join(map(lambda (x, y): "%s=%s" % (x, y), sorted(headers.items())))
)
start_sign_time = int(time.time())
sign_time = "{bg_time};{ed_time}".format(bg_time=start_sign_time-60, ed_time=start_sign_time self._expire)
sha1 = hashlib.sha1()
sha1.update(format_str)
str_to_sign = "sha1n{time}n{sha1}n".format(time=sign_time, sha1=sha1.hexdigest())
sign_key = hmac.new(self._secret_key, sign_time, hashlib.sha1).hexdigest()
sign = hmac.new(sign_key, str_to_sign, hashlib.sha1).hexdigest()
sign_tpl = "q-sign-algorithm=sha1&q-ak={ak}&q-sign-time={sign_time}&q-key-time={key_time}&q-header-list={headers}&q-url-param-list={params}&q-signature={sign}"
print ('sign_key',sign_key)
r.headers['Authorization'] = sign_tpl.format(
ak=self._secret_id,
sign_time=sign_time,
key_time=sign_time,
params=';'.join(sorted(map(lambda k: k.lower(), uri_params.keys()))),
headers=';'.join(sorted(headers.keys())),
sign=sign
)
return r
if __name__ == "__main__":
secret_id = 'AKIDyL'
secret_key = '9Palu'
method = 'GET'
cos_path = '/'
res = requests.Request(method, cos_path)
auth = CosS3Auth(secret_id=secret_id, secret_key=secret_key, key=cos_path)
sign = auth(res).headers['Authorization']
print ('sign',sign)
注意:
合理修改其中的
secret_id = ##api密钥id
secret_key = ##api密钥key
method = ##请求方式
cos_path ##请求路径
执行结果: sign部分为签名信息