Bytes message argument error

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

I can't figure out what the 'bytes' method is complaining about. In the code below, i am trying to generate an authentication key for my client and i keep getting this error [1]

import hmac import hashlib import base64  message = bytes("Message", 'utf-8') # errors here secret = bytes("secret", 'utf-8')  signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest()); print(signature) 

[1]

Traceback (most recent call last):   File "API/test/auth-client.py", line 11, in <module>     message = bytes("Message", 'utf-8') TypeError: str() takes at most 1 argument (2 given) 

回答1:

bytes() in Python 2.x is the same as str() and it accepts only one string argument.

Use just message = "Message" and secret = "secret". You don't even need bytes() here.



回答2:

The likely reason you encountered this problem is the code you were using was written for Python 3.x and you executed it under Python 2.x.

I know someone has already partially stated this, but I thought it might be helpful to make it clearer to people new to Python who may not realize why the 'utf-8' argument was being used as the person asking the question noted that they did not know what the argument was for.

Anyone who comes here may find that useful in understanding why there was an argument of 'utf-8'.



回答3:

try,

import hmac import hashlib import base64  message = bytes("Message") secret = bytes("secret")  signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest()) print(signature) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!