Python TypeError - 尝试创建签名时需要字节但得到“str”

2024-04-13

我正在尝试为 API 调用创建签名 - 文档提供了以下说明:

timestamp = str(int(time.time()))
    message = timestamp + request.method + request.path_url + (request.body or '')
    signature = hmac.new(self.secret_key, message, hashlib.sha256).hexdigest()

但是,我总是收到此错误:

Exception has occurred: TypeError key: expected bytes or bytearray, but got 'str' 

File "/Users/dylanbrandonuom/BouncePay_Code/src/coinbase/Coinbase_API.py", line 26, in __call__
signature = hmac.new(self.secret_key, message, hashlib.sha256).hexdigest()

File "/Users/dylanbrandonuom/BouncePay_Code/src/coinbase/Coinbase_API.py", line 40, in <module>
r = requests.get(api_url + 'user', auth=auth)

我尝试过改变

signature = hmac.new(self.secret_key, message, hashlib.sha256).hexdigest()

to

signature = hmac.new(b'self.secret_key', message, hashlib.sha256).hexdigest()

但没有成功。

这是错误的第二部分:

api_url = 'https://api.coinbase.com/v2/'
auth = CoinbaseWalletAuth(API_KEY, API_SECRET)
r = requests.get(api_url + 'user', auth=auth)

有谁能让我知道为什么这种情况不断发生?

我想这可能是消息变量request.method and request.path_url,但我不确定。


您看到的错误消息告诉您正在传递一个 (unicode) 字符串作为key论证hmac.new(),但它需要字节(或字节数组)。

这意味着self.secret_key是一个字符串,而不是一个字节对象。你的问题没有表明你的代码在哪里self.secret_key正在被分配,但假设它是某个地方的常量,它可能看起来像这样:

SECRET = 'some secret key'

如果是这样,将该行更改为类似的内容

SECRET = b'some secret key'

…应该可以工作。如果您要分配self.secret_key换句话说,如果不看到该代码,就不可能知道如何解决问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python TypeError - 尝试创建签名时需要字节但得到“str” 的相关文章

随机推荐