55from hashlib import sha1
66from requests .auth import AuthBase
77from .compat import urlparse , json , b
8- from .utils import urlsafe_base64_encode
8+ from .utils import urlsafe_base64_encode , canonical_mime_header_key
99
1010# 上传策略,参数规格详见
1111# https://developer.qiniu.com/kodo/manual/1206/put-policy
@@ -58,6 +58,9 @@ def __init__(self, access_key, secret_key):
5858 def get_access_key (self ):
5959 return self .__access_key
6060
61+ def get_secret_key (self ):
62+ return self .__secret_key
63+
6164 def __token (self , data ):
6265 data = b (data )
6366 hashed = hmac .new (self .__secret_key , data , sha1 )
@@ -265,15 +268,21 @@ def token_of_request(
265268 path_with_query = path
266269 if query != '' :
267270 path_with_query = '' .join ([path_with_query , '?' , query ])
268- data = '' .join (["%s %s" %
269- (method , path_with_query ), "\n " , "Host: %s" %
270- host , "\n " ])
271+ data = '' .join ([
272+ "%s %s" % (method , path_with_query ),
273+ "\n " ,
274+ "Host: %s" % host
275+ ])
271276
272277 if content_type :
273- data += "Content-Type: %s" % (content_type ) + "\n "
278+ data += "\n "
279+ data += "Content-Type: %s" % content_type
280+
281+ if qheaders :
282+ data += "\n "
283+ data += qheaders
274284
275- data += qheaders
276- data += "\n "
285+ data += "\n \n "
277286
278287 if content_type and content_type != "application/octet-stream" and body :
279288 if isinstance (body , bytes ):
@@ -283,11 +292,13 @@ def token_of_request(
283292 return '{0}:{1}' .format (self .__access_key , self .__token (data ))
284293
285294 def qiniu_headers (self , headers ):
286- res = ""
287- for key in headers :
288- if key .startswith (self .qiniu_header_prefix ):
289- res += key + ": %s\n " % (headers .get (key ))
290- return res
295+ qiniu_fields = list (filter (
296+ lambda k : k .startswith (self .qiniu_header_prefix ) and len (k ) > len (self .qiniu_header_prefix ),
297+ headers ,
298+ ))
299+ return "\n " .join ([
300+ "%s: %s" % (canonical_mime_header_key (key ), headers .get (key )) for key in sorted (qiniu_fields )
301+ ])
291302
292303 @staticmethod
293304 def __checkKey (access_key , secret_key ):
@@ -300,6 +311,8 @@ def __init__(self, auth):
300311 self .auth = auth
301312
302313 def __call__ (self , r ):
314+ if r .headers .get ('Content-Type' , None ) is None :
315+ r .headers ['Content-Type' ] = 'application/x-www-form-urlencoded'
303316 token = self .auth .token_of_request (
304317 r .method , r .headers .get ('Host' , None ),
305318 r .url , self .auth .qiniu_headers (r .headers ),
0 commit comments