Python - 我的包名称和已安装的包名称之间的冲突



我正在尝试调用PyJWT函数jwt.encode但它可能与我的包jwt冲突,因此错误AttributeError("module 'jwt' has no attribute 'encode'")

  • 我正在运行一个虚拟环境。
  • Python 版本 3.6.7
  • 根据 Python 版本 3.x 中的答案,这应该不是问题。

我的申请结构如下

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

运行时出现错误

(venv) ~$ pytest

我在文件夹中放了一个空__init__.py tests因为否则它找不到我的jwt包。

下面是db.py内部的函数调用jwt.encode

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

修复:重命名目录jwt

原因:由于您的代码在PYTHONPATH库中的代码之前,因此可以看到您的代码,而不是来自PyJWTjwt

例:

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

最新更新