Python TypeError-预期的字节数,但是在尝试创建签名时得到了"str" [英] Python TypeError - Expected bytes but got 'str' when trying to created signature

查看:111
本文介绍了Python TypeError-预期的字节数,但是在尝试创建签名时得到了"str"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a signature for an API call - for which the documentation provides these instructions:

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()

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

However, I always get this error:

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)

有人能让我知道为什么这种情况持续发生吗?

Is anyone able to let me know why this keeps occurring?

我认为这可能是带有 request.method request.path_url 的消息变量,但我不确定.

I'm thinking it might be the message variable with request.method and request.path_url, but I'm not sure.

推荐答案

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

The error message you're seeing tells you that you're passing a (unicode) string as the key argument to hmac.new(), but it expects bytes (or a bytearray).

这意味着 self.secret_key 是字符串,而不是字节对象.您的问题中没有迹象表明在代码中 self.secret_key 的位置被分配了,但是假设它在某个地方是一个常数,则可能看起来像这样:

This means that self.secret_key is a string, rather than a bytes object. There's no indication in your question where in your code self.secret_key is being assigned, but on the assumption that it's a constant somewhere, it might look like this:

SECRET = 'some secret key'

如果是这样,请将该行更改为

If so, changing that line to something like

SECRET = b'some secret key'

...应该工作.如果您以其他方式分配 self.secret_key ,那么在没有看到该代码的情况下就不可能知道如何解决该问题.

… ought to work. If you're assigning self.secret_key in some other way, it's impossible to know how to fix the problem without seeing that code.

这篇关于Python TypeError-预期的字节数,但是在尝试创建签名时得到了"str"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆