fastapi:访问mysql时报错:RuntimeError: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods

一,报错信息:

RuntimeError: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods

原因:

这个错误在 FastAPI(或者更准确地说是底层使用的 PyMySQL 等数据库驱动)连接 MySQL 8.0+ 数据库时非常常见。

根本原因在于:MySQL 8.0 及以上版本默认使用了更安全的加密认证方式(caching_sha2_passwordsha256_password),而你的 Python 环境中缺少用于解密的 cryptography 库。

 

二,解决:

如果你在 SQLAlchemy 的连接字符串(DATABASE_URL)中使用的是 mysql+pymysql://...,PyMySQL 在处理 MySQL 8.0 的加密密码时,必须依赖 cryptography 库。
如果没安装,就会抛出这个错误。

解决办法: 在你的虚拟环境中安装该库:

$ pip install cryptography

 

posted @ 2026-06-12 10:53  刘宏缔的架构森林  阅读(12)  评论(0)    收藏  举报