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

FastAPI向MySQL插入数据时触发TypeError错误的解决方法

问题解决:FastAPI返回数据库查询结果时的序列化错误

错误原因

你返回的conn.execute(users.select()).fetchall()是数据库原生的行对象集合,FastAPI的序列化器无法直接将这些行对象转换为JSON可识别的格式,尝试将其转为字典时触发了类型错误。

解决方法

方法1:将查询结果转为字典列表

把数据库行对象逐个转为字典,让FastAPI能正常序列化:

@user.post("/add-user")
async def write_user_date(user: User):
    # 插入数据
    conn.execute(users.insert().values(
        name=user.name,
        email=user.email,
        password=user.password,
    ))
    # 提交事务(如使用SQLite等需手动提交的数据库)
    conn.commit()
    # 查询结果转为字典列表后返回
    result = conn.execute(users.select()).fetchall()
    return [dict(row) for row in result]

方法2:基于SQLAlchemy ORM模型序列化(若使用ORM)

如果你的项目用SQLAlchemy ORM定义了User模型,可以直接返回模型实例,FastAPI会自动处理序列化:

from sqlalchemy.orm import Session
from your_module import UserModel, get_db  # 导入你的ORM模型和数据库会话依赖

@user.post("/add-user")
async def write_user_date(user: User, db: Session = Depends(get_db)):
    db_user = UserModel(name=user.name, email=user.email, password=user.password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    # 返回所有用户ORM实例,自动序列化
    return db.query(UserModel).all()

额外注意事项

  • 若使用需要手动提交的数据库(如SQLite),插入数据后必须调用conn.commit(),否则数据不会持久化到数据库。
  • 永远避免直接返回数据库原生行对象,需转为字典、ORM实例等可JSON序列化的格式。

内容的提问来源于stack exchange,提问作者Nowshad Ruhani Chowdhury

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:05:28