1

I am trying to call jwt.encode function of PyJWT but it's probably conflicting with my package jwt and thus giving the error AttributeError("module 'jwt' has no attribute 'encode'")

  • I am running a virtual environment.
  • Python version 3.6.7
  • According the answer here in Python versions 3.x this shouldn't be a problem.

My application structure is as below

jwt
 |-- __init__.py
 |-- db.py
instance
 |-- jwt.sqlite
tests
 |-- __init__.py
 |-- conftest.py
 |-- test_encodetoken.py

I get the error when I run

(venv) ~$ pytest

I put an empty __init__.py in tests folder because otherwise it cannot find my jwt package.

Below is the function calling jwt.encode which is inside db.py

import jwt
def encode_auth_token(user_id,app):
    """
    Generates the Auth Token
    :return: string
    """
    try:
        payload = {
            'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=5),
            'iat': datetime.datetime.utcnow(),
            'sub': user_id
        }
        return jwt.encode(
            payload,
            app.config.get('SECRET_KEY'),
            algorithm='HS256'
        )
    except Exception as e:
        return e
davidism
  • 121,510
  • 29
  • 395
  • 339
S.aad
  • 518
  • 1
  • 5
  • 22

1 Answers1

1

Fix: Rename the directory jwt

Why: Since your code is before the library's code in the PYTHONPATH you code is seen and not the jwt from PyJWT

Example:

dbutils
 |-- __init__.py
 |-- db.py
instance
 |-- jwt.sqlite
tests
 |-- __init__.py
 |-- conftest.py
 |-- test_encodetoken.py
JBirdVegas
  • 10,855
  • 2
  • 44
  • 50
  • I would like to understand the concept behind `PYTHONPATH` a bit more so I am able to import the library code if such an issue occurs again. Could you suggest how can I do that? – S.aad Mar 26 '19 at 08:05