Python JWT:“模块”对象没有“编码”属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33198428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JWT: 'module' object has no attribute 'encode'
提问by Arvind Kandaswamy
I am getting a Module not found errorwhen using jwt
. Here is how I declared it:
我得到一个模块未找到错误使用时jwt
。这是我声明的方式:
def create_jwt_token():
payload = {
"iat": int(time.time())
}
shared_key = REST_API_TOKEN
payload['email'] = EMAIL
payload['password'] = PASSWORD
jwt_string = jwt.encode(payload, shared_key)
encoded_jwt = urllib.quote_plus(jwt_string) # URL encode the JWT string
return encoded_jwt
The error message says encode is not found in jwt
. I did a tab on jwt
and found that the encode is a method inside jwt.JWT
. I tried changing it to
错误消息说在jwt
. 我做了一个选项卡jwt
,发现编码是jwt.JWT
. 我试着把它改成
jwt_string = jwt.JWT.encode(payload, shared_key)
and it gives this error:
它给出了这个错误:
unbound method encode() must be called with JWT instance as first argument (got dict instance instead)
必须使用 JWT 实例作为第一个参数调用未绑定的方法 encode()(改为使用 dict 实例)
What am I doing it wrong? Here is the version information of my Python environment:
我做错了什么?下面是我的Python环境的版本信息:
2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 16:44:52) [MSC v.1500 64 bit (AMD64)]
2.7.10 |蟒蛇 2.3.0(64 位)| (默认,2015 年 5 月 28 日,16:44:52)[MSC v.1500 64 位 (AMD64)]
回答by Arvind Kandaswamy
After trying several workarounds, I created a new Python notebook with the same code and it appears to be working. I am not sure what was the issue before.
在尝试了几种解决方法后,我使用相同的代码创建了一个新的 Python 笔记本,它似乎可以正常工作。我不确定之前是什么问题。
回答by poxip
You can use the PyJWT package, where jwt.encode()
works fine (no need for initialization or other kinds of stuff).
您可以使用PyJWT 包,在那里jwt.encode()
工作正常(不需要初始化或其他类型的东西)。
回答by Joshua
The problem arises if you have both JWT and PyJWT installed. When doing import jwt
it is importing the library JWT as opposed to PyJWT - the latter is the one you want for encoding. I did pip uninstall JWT
and pip uninstall PyJWT
then finally pip install PyJWT
. After that it imported the correct module and generated the token! :)
如果您同时安装了 JWT 和 PyJWT,就会出现问题。这样做import jwt
是导入库 JWT 而不是 PyJWT - 后者是您想要的编码。我做了pip uninstall JWT
,pip uninstall PyJWT
然后终于pip install PyJWT
。之后它导入了正确的模块并生成了令牌!:)
回答by Aarya
I was also facing the same issue because I had named the script from which I had been calling jwt.encode() as 'jwt.py'. So be careful while naming scripts. Try not to use any library names.
我也面临同样的问题,因为我已经将调用 jwt.encode() 的脚本命名为“jwt.py”。所以命名脚本时要小心。尽量不要使用任何库名称。