【发布时间】:2021-09-02 22:17:58
【问题描述】:
我有一些 Pydantic 对象,我试图使用 __init__ 更新字段(例如时间)或发送事件,但每次我从 FastAPI 处理程序返回 Pydantic 对象时都会调用这些事件。
简化示例
class OtherModel(BaseModel):
value: int
class SomeModel(BaseModel):
other: OtherModel
@validator('other', pre=True, always=True)
def are_items_in_order(cls, other):
cur_val = 0
if cur_val > other.value:
raise ValueError('out of order')
return other
def some_function() -> SomeModel:
val1 = OtherModel(value=1)
something = SomeModel(other=val1)
print(something)
return something
@app.get("/test", response_model=SomeModel)
async def exec_test():
something = some_function()
print(something)
return something
第一次打印的输出看起来不错
other=OtherModel(value=1)
other=OtherModel(value=1)
然后我从 Pydantic 收到一个错误,因为它正在尝试执行我的验证器,但现在使用 dict 而不是对象
if cur_val > other.value:
AttributeError: 'dict' object has no attribute 'value'
如何处理或避免这种故障?
【问题讨论】: