Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

jwt

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

like image 215
Arvind Kandaswamy Avatar asked Oct 18 '15 13:10

Arvind Kandaswamy


2 Answers

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

like image 88
Joshua Avatar answered Sep 25 '22 00:09

Joshua


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.

like image 41
Aarya Avatar answered Sep 27 '22 00:09

Aarya