2017-01-11 42 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

相关问题