gpt4 book ai didi

python - 类型错误 : Can't convert 'bytes' object to str implicitly - Python

转载 作者:行者123 更新时间:2023-12-01 03:24:14 26 4
gpt4 key购买 nike

我正在尝试为我尝试在 Python 中使用的 API 创建身份验证签名,我正在尝试的是,

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 身份验证 header 中。

以上内容直接取自文档,以下是我的尝试,

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

错误来 self 的代码示例的最后一行。

最佳答案

我想你的代码是 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)

关于python - 类型错误 : Can't convert 'bytes' object to str implicitly - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41588847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com