FastAPI 与 Pydantic 验证器对其他模型的组合
FastAPI with Pydantic validator on composition of other models
我有一些 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'
如何处理或避免这种故障?
您似乎希望单独验证每个列表值(将其与 0 进行比较),each_item=True validator 应该适合您
我有一些 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'
如何处理或避免这种故障?
您似乎希望单独验证每个列表值(将其与 0 进行比较),each_item=True validator 应该适合您