2017-01-11 47 views
1

我想創建一個API我想在Python消耗的認證簽名,我想做的就是,類型錯誤:無法將「字節」對象隱含str的 - Python的

1)簽名是通過使用URI的查詢字符串部分的副本創建的,其示例如下所示。

?customerId=johns Trucks&userName=BobH&timeStamp=2014-05-01T11:00:00Z

2)確保您使用編碼UTF8編碼私鑰。一旦編碼,您可以使用您的私鑰創建您的簽名

3)將從步驟2創建的簽名轉換爲base64。

4)如果我們使用fakekey的私鑰,對於上面的URI字符串像這樣已經計算了HMAC-SHA1後,再轉換爲Base64

PeKNVo1BAiuZyHxIdMisidG92bg=

5簽名)的現在可以將簽名添加到請求的Http驗證標頭中。

以上選自直取自文檔和下面是我的嘗試,

private_key = bytes("auth", encoding='utf-8'); 
public_key = bytes("200000", encoding='utf-8'); 
customer_id = "HFH"; 
username = "API"; 

date_utc = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ") 
message = bytes('?customerId=HFH&userName=API&timeStamp=' + date_utc, encoding='utf-8') 

signature = base64.b64encode(hmac.new(private_key, message, digestmod=hashlib.sha1).digest()) 
encoded_sig = base64.b64encode(signature) 

url = 'https://xxx.xxxxxxx.net/api/FleetVehicles?customerId=HFH&userName=API&timeStamp=' + date_utc; 

data = requests.get(url, headers={'authorization:' + public_key + ":" + encoded_sig}); 

我的代碼是導致以下錯誤,

TypeError: Can't convert 'bytes' object to str implicitly

誤差從最後一行到來我的代碼示例。

回答

1

我想你的代碼是Python 3的

與Python 3開始,現在字符串表示無論是作爲的unicode字符串二進制數據說明here

Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. All text is Unicode; however encoded Unicode is represented as binary data. The type used to hold text is str, the type used to hold data is bytes. The biggest difference with the 2.x situation is that any attempt to mix text and data in Python 3.0 raises TypeError, whereas if you were to mix Unicode and 8-bit strings in Python 2.x, it would work if the 8-bit string happened to contain only 7-bit (ASCII) bytes, but you would get UnicodeDecodeError if it contained non-ASCII values.

你想要什麼這裏是:

headers={b'authorization:' + public_key + b":" + encoded_sig}) 

(注意b靜態字符串)

或之前:

headers={'authorization:' + public_key.decode('utf-8') + ":" + encoded_sig.decode('utf-8')}) 

(注意.decode()轉換您字節STR

相關問題