Python TypeError - 预期的字节数,但在尝试创建签名时得到 'str'
Python TypeError - Expected bytes but got 'str' when trying to created signature
我正在尝试为 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()
到
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
和 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
,那么不看代码就不可能知道如何解决问题。
我正在尝试为 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()
到
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
和 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
,那么不看代码就不可能知道如何解决问题。