迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中 AttributeError module 'jwt' has no attribute 'encode' 错误

作者:迹忆客 最近更新:2023/01/02 浏览次数:

当我们有一个名为 jwt.py 的本地文件并从 PyJWT 模块导入时,会出现 Python“AttributeError module 'jwt' has no attribute 'encode' ”。 要解决该错误,需要确保我们没有名为 jwt.py 的文件,卸载 jwt 模块并安装 PyJWT。

首先,确保我们没有安装 jwt 模块而不是 PyJWT。

# 👇️ 卸载 jwt 和 PyJWT
$ pip3 uninstall jwt
$ pip3 uninstall PyJWT

# 👇️ 安装 PyJWT
$ pip3 install PyJWT

现在尝试导入 jwt 模块。

import jwt

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

print(encoded)

print(jwt.decode(encoded, "secret", algorithms=["HS256"]))

确保您没有名为 jwt.py 的本地文件。

如果我们有一个名为 jwt.py 的本地模块,它将隐藏第三方 PyJWT 模块。

下面是一个名为 jwt.py 的本地文件中发生错误的示例。

import jwt

# ⛔️ AttributeError: partially initialized module 'jwt' has no
#  attribute 'encode' (most likely due to a circular import).
encoded = jwt.encode({"some": "payload"}, "secret", algorithm="HS256")

print(encoded)

print(jwt.decode(encoded, "secret", algorithms=["HS256"]))

Python 解释器首先在内置模块中查找导入的模块,然后在当前目录中查找,然后在 PYTHON PATH 中查找,最后在依赖于安装的默认目录中查找。

因此,当我们创建一个与第三方模块同名的本地文件时,我们实际上用我们的本地文件隐藏了官方模块。

它不必是我们直接运行的文件。 如果目录中的任何位置都有 jwt.py 文件,它会影响官方模块。

我们可以访问导入模块的 __file__ 属性以查看它是否被本地文件隐藏。

import jwt

print(jwt.__file__)


# ⛔️ result if shadowed by local file
# /home/borislav/Desktop/bobbyhadz_python/jwt.py

# ✅ result if pulling in correct module
# /home/borislav/Desktop/bobbyhadz_python/venv/lib/python3.10/site-packages/jwt/__init__.py

开始调试的一个好方法是 print(dir(your_module)) 并查看导入的模块具有哪些属性。

import jwt

# ✅ ['__builtins__', '__cached__', '__doc__', '__file__',
#  '__loader__', '__name__', '__package__', '__spec__', 'jwt']
print(dir(jwt))

如果将模块对象传递给 dir() 函数,它会返回模块属性名称的列表。

如果我们尝试访问不在此列表中的任何属性,我们将得到“AttributeError: module 'jwt' has no attribute 'encode'”。

我们可以看到模块的属性中没有编码方法,这清楚地表明我们正在用我们的本地模块隐藏第三方模块。

确保我们没有在 import 语句中拼错任何内容,因为这也可能导致错误。

重命名文件后,我们应该能够使用 PyJWT 模块。

import jwt

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

print(encoded)

print(jwt.decode(encoded, "secret", algorithms=["HS256"]))

总结

当我们有一个名为 jwt.py 的本地文件并从 PyJWT 模块导入时,会出现 Python“AttributeError module 'jwt' has no attribute 'encode'”。 要解决该错误,请确保您没有名为 jwt.py 的文件,卸载 jwt 模块并安装 PyJWT。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便