fastapi: 报错:Error extracting attribute: MissingGreenlet: greenlet_spawn has not been called; can't call await_() here. Was IO attempted in an unexpected place?
一,报错信息:
File "/Users/apple/Documents/project/fast_scaf2/app/admin/api/staffadmin_api.py", line 201, in register
dict = StaffResponse.model_validate(user).model_dump()
File "/Users/apple/Documents/project/fast_scaf2/venv/lib/python3.14/site-packages/pydantic/main.py", line 732, in model_validate
return cls.__pydantic_validator__.validate_python(
pydantic_core._pydantic_core.ValidationError: 1 validation error for StaffResponse
created_at
Error extracting attribute: MissingGreenlet: greenlet_spawn has not been called;
can't call await_() here. Was IO attempted in an unexpected place?
(Background on this error at: https://sqlalche.me/e/21/xd2s)
[type=get_attribute_error, input_value=<unprintable AppUserModel object>, input_type=AppUserModel]
For further information visit https://errors.pydantic.dev/2.13/v/get_attribute_error
二,原因
这个错误是因为在异步 SQLAlchemy(AsyncSession)环境中,Pydantic 的
但该属性尚未被加载(Lazy Loading)。在异步模型中,直接触发延迟加载会引发
model_validate(user) 试图去读取 user 对象上的 created_at 属性,但该属性尚未被加载(Lazy Loading)。在异步模型中,直接触发延迟加载会引发
MissingGreenlet 异常。当
如果你的
SQLAlchemy 试图发起同步的 I/O 请求,这在异步驱动中是被禁止的。
from_attributes=True(Pydantic v2)开启时,model_validate 会通过 getattr(user, 'created_at') 读取字段。如果你的
created_at 字段需要数据库 I/O 才能加载(例如由于没有包含在查询中、属于关联对象,或因 Session 已经关闭/属性过期),SQLAlchemy 试图发起同步的 I/O 请求,这在异步驱动中是被禁止的。
三,解决:
果在创建或修改
user 后,其状态变为了过期(Expired),请在传入 Pydantic 之前,使用异步方法手动将其加载或刷新:# 在调用 model_validate 之前
await db.refresh(user, ["created_at"]) # 显式刷新该属性
# 随后再执行验证即可成功
dict = StaffResponse.model_validate(user).model_dump()
浙公网安备 33010602011771号