Python TypeError - Expected Bytes But Got 'str' When Trying To Created Signature
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)
I've tried changing
signature = hmac.new(self.secret_key, message, hashlib.sha256).hexdigest()
signature = hmac.new(b'self.secret_key', message, hashlib.sha256).hexdigest()
but had no success.
Here is the second part of the error:
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?
I'm thinking it might be the message variable with
request.path_url, but I'm not sure.
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).
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'
… 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.
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module