JWT: 'module' object has no attribute 'encode'

Arvind Kandaswamy picture Arvind Kandaswamy · Oct 18, 2015 · Viewed 38k times · Source

I am getting a Module not found error when using jwt. Here is how I declared it:

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_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)

What am I doing it wrong? Here is the version information of my Python environment:

2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 16:44:52) [MSC v.1500 64 bit (AMD64)]

Answer

Joshua picture Joshua · Dec 21, 2015

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