【问题标题】:Python TypeError - Expected bytes but got 'str' when trying to created signaturePython TypeError - 尝试创建签名时预期字节但得到'str'
【发布时间】:2019-03-18 08:49:52
【问题描述】:

我正在尝试为 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.methodrequest.path_url 的消息变量,但我不确定。

【问题讨论】:

    标签: python python-3.x python-requests hmac coinbase-api


    【解决方案1】:

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

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

    SECRET = 'some secret key'
    

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

    SECRET = b'some secret key'
    

    ……应该可以工作。如果您以其他方式分配self.secret_key,则不查看该代码就不可能知道如何解决问题。

    【讨论】:

    • 原来如此。我已将它们声明为字符串。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 2021-02-11
    • 2014-09-22
    • 2021-10-14
    相关资源
    最近更新 更多