You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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),安装最新版即可修复:
    pip install --upgrade sqlacodegen
    
    版本>=2.4.0已适配Python 3.11。
  • 临时手动修复(不推荐):若无法升级,可修改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生成迁移文件时可提取模型代码:
    1. 初始化Alembic:alembic init alembic
    2. 修改alembic.ini中的数据库URL
    3. 在alembic/env.py中配置target_metadata指向模型元数据
    4. 执行alembic revision --autogenerate生成迁移文件,从中提取模型定义
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 05:25:24