我試圖做一個Twitter的權威性和Django中間件的幫助下,我在那裏計算這樣的請求的簽名(https://dev.twitter.com/oauth/overview/creating-signatures):Python的HMAC散列值編碼爲base64
key = b"MY_KEY&"
raw_init = "POST" + "&" + quote("https://api.twitter.com/1.1/oauth/request_token", safe='')
raw_params = <some_params>
raw_params = quote(raw_params, safe='')
#byte encoding for HMAC, otherwise it returns "expected bytes or bytearray, but got 'str'"
raw_final = bytes(raw_init + "&" + raw_params, encoding='utf-8')
hashed = hmac.new(key, raw_final, sha1)
request.raw_final = hashed
# here are my problems: I need a base64 encoded string, but get the error "'bytes' object has no attribute 'encode'"
request.auth_header = hashed.digest().encode("base64").rstrip('\n')
正如你所看到的,沒有辦法base64編碼一個'字節'對象。
提出的解決方案在這裏:Implementaion HMAC-SHA1 in python
你試過了:'base64.encodestring(str(raw_final))'? –
@ Jean-FrançoisFabre我爲什麼要編碼raw_final?我需要一個HMAC對象轉換爲base64字符串...所有這些根據twitter文檔 - https://dev.twitter.com/oauth/overview/creating-signatures在頁面的最底部 –