‘ module’对象没有属性‘ encode’

当我使用 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

错误消息说在 jwt中找不到编码。我在 jwt上做了一个选项卡,发现该编码是 jwt.JWT内部的一个方法。我试过改成

jwt_string = jwt.JWT.encode(payload, shared_key)

它给出了这个错误:

Unbound 方法 encode ()必须用 JWT 实例作为第一个参数来调用(而是使用 dict 实例)

我做错了什么? 下面是我的 Python 环境的版本信息:

2.7.10 | Anaconda 2.3.0(64位) | (默认,2015年5月28日,16:44:52)[ MSC v. 150064位(AMD64)]

107700 次浏览

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.

You can use the PyJWT package, where jwt.encode() works fine (no need for initialization or other kinds of stuff).

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! :)

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.

Use PyJWT instead. I faced the same issue with jwt so I uninstalled it and used PyJWT instead.

I solved this problem and @josua's answer is correct I would like to answer with details. In my case, pyJwt was already installed. I was using getream client

And then I was trying to install jwt using: jwt package

And it is a known issue Issue Related to JWT

So the actual problem is a quote from Yoshida:

Unfortunately, no. As of now both libraries use the same jwt module namespace and Python's module system cannot resolve import jwt deterministically.

So I checked my pip freeze and jwt was installed and I fixed this issue by using these commands:

pip uninstall jwt==1.0.0
pip uninstall PyJWT
pip install PyJWT

And now my code:

encoded = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')

works fine.

Apart from (re)installing the PyJWT dependency through pip which other answers already mention make sure following files are not in the current directory (i.e. pwd) you're either running python in or your .py script:

jwt.py
token.py

In my case, I just needed to do

pip install pyjwt

this worked for me:

pip install djangorestframework-jwt==1.11.0

This worked for me:

pip uninstall Flask-JWT && pip install Flask-JWT