Python 中 AttributeError module 'jwt' has no attribute 'encode' 错误 您所在的位置:网站首页 python模块删除 Python 中 AttributeError module 'jwt' has no attribute 'encode' 错误

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

2023-01-03 11:44| 来源: 网络整理| 查看: 265

当前位置:主页 > 学无止境 > 编程语言 > WEB前端 编程语言 网络 算法 操作系统 数据库 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。

上一篇:Python 中 AttributeError module 'json' has no attribute 'dumps' 错误

下一篇:JavaScript 引擎基础:优化原型链

本站文章均为原创或翻译,转载请发邮件至 [email protected] 进行申请,未经许可,禁止转载。经作者同意之后,转载请以链接形式注明出处

本文地址:



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有