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

Serverless FastAPI课程中/api/open-tasks接口Pydantic ValidationError求助

问题:FastAPI + Pydantic ValidationError:value is not a valid dict

问题详情

正在学习《Serverless Apps with FastAPI, DynamoDB, and Vue》课程,在第一部分API章节执行测试时遇到Pydantic验证错误。执行命令:

$ poetry run pytest tests.py

测试失败,报错如下。已严格按照课程步骤操作,但测试未通过。

错误信息

>   ???
E   pydantic.error_wrappers.ValidationError: 1 validation error for APITaskList
E   results -> 0
E     value is not a valid dict (type=type_error.dict)

pydantic/main.py:341: ValidationError
============================================= short test summary info ============================
FAILED tests.py::test_list_open_tasks - pydantic.error_wrappers.ValidationError: 1 validation error for APITaskList

相关代码

测试请求

response = client.get("/api/open-tasks", headers={"Authorization": id_token})

(client 为FastAPI TestClient夹具)

接口路由

@app.get("/api/open-tasks", response_model=APITaskList)
def open_tasks(
    user_email: str = Depends(get_user_email),
    task_store: TaskStore = Depends(get_task_store),
):
    return APITaskList(results=task_store.list_open(owner=user_email))

Pydantic模型

class APITaskList(BaseModel):
    results: list[APITask]

    class Config:
        orm_mode = True
class APITask(BaseModel):
    id: UUID
    title: str
    status: TaskStatus
    owner: str

    class Config:
        orm_mode: True

解决方案

这个错误的核心是:task_store.list_open() 返回的列表中,第一个元素无法被Pydantic解析成APITask实例,Pydantic认为它不是有效的字典或ORM对象。

排查步骤与修复建议

  1. 检查task_store.list_open()的返回值类型
    在路由函数中临时添加打印语句,查看返回的每个元素类型和结构:

    tasks = task_store.list_open(owner=user_email)
    print(type(tasks[0]))
    print(tasks[0])
    return APITaskList(results=tasks)
    

    如果返回的是DynamoDB的原始响应(比如boto3的Item对象,或者字符串格式的数据),需要先转换成符合APITask结构的字典或ORM模型实例。

  2. 确保字段类型匹配

    • 如果id字段从DynamoDB返回的是字符串,需要手动转换为UUID类型:
      # 示例:在task_store.list_open中处理id字段
      from uuid import UUID
      task_dict["id"] = UUID(task_dict["id"])
      
    • 检查TaskStatus枚举是否与DynamoDB中存储的状态值完全匹配(比如大小写、字符串内容),枚举不匹配也可能触发验证错误。
  3. 验证ORM_MODE是否生效
    虽然开启了orm_mode = True,但如果task_store返回的对象不是标准的ORM模型(比如没有__dict__属性或__getattr__方法),Pydantic无法自动解析。此时需要手动将对象转换为字典:

    # 路由中转换为字典列表
    return APITaskList(results=[task.__dict__ for task in tasks])
    

内容的提问来源于stack exchange,提问作者mathlino

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:10:19