使用sqlacodegen生成PostgreSQL模型遇ArgSpec导入错误求助
sqlacodegen Python3.11导入错误解决及替代方案
环境与问题
当前使用环境:Python 3.11、PostgreSQL、SQLAlchemy 2.0.15、sqlacodegen 2.3.0
执行命令自动生成FastAPI数据库模型:
sqlacodegen postgresql://postgres:j1234@localhost:4040/db1
触发以下导入错误:
Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\user\AppData\Local\Programs\Python\Python311\Scripts\sqlacodegen.exe\__main__.py", line 4, in <module> File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\sqlacodegen\main.py", line 11, in <module> from sqlacodegen.codegen import CodeGenerator File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\sqlacodegen\codegen.py", line 9, in <module> from inspect import ArgSpec ImportError: cannot import name 'ArgSpec' from 'inspect' (C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\inspect.py)
解决方法
- 升级sqlacodegen至兼容版本:sqlacodegen 2.3.0不支持Python 3.11(Python 3.10起已移除
inspect.ArgSpec),安装最新版即可修复:
版本>=2.4.0已适配Python 3.11。pip install --upgrade sqlacodegen - 临时手动修复(不推荐):若无法升级,可修改
C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\sqlacodegen\codegen.py,将from inspect import ArgSpec替换为from inspect import FullArgSpec as ArgSpec,但此方法可能引发其他兼容性问题,优先推荐升级。
替代工具推荐
- SQLAlchemy Alembic Autogenerate:SQLAlchemy官方工具,通过Alembic生成迁移文件时可提取模型代码:
- 初始化Alembic:
alembic init alembic - 修改
alembic.ini中的数据库URL - 在
alembic/env.py中配置target_metadata指向模型元数据 - 执行
alembic revision --autogenerate生成迁移文件,从中提取模型定义
- 初始化Alembic:
- pydantic-sqlalchemy:直接从SQLAlchemy模型生成适配FastAPI的Pydantic Schema:
from pydantic_sqlalchemy import sqlalchemy_to_pydantic from your_sqlalchemy_models import User UserPydantic = sqlalchemy_to_pydantic(User) - fastapi-sqlalchemy-crud-generator:专为FastAPI设计,可直接从数据库生成完整的CRUD接口及对应模型,支持PostgreSQL等主流数据库。
内容的提问来源于stack exchange,提问作者Juned SK
相关产品推荐
相关产品推荐

