【问题标题】:FastAPI with Pydantic validator on composition of other models带有 Pydantic 验证器的 FastAPI 用于其他模型的组合
【发布时间】: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'

如何处理或避免这种故障?

【问题讨论】:

    标签: python fastapi pydantic


    【解决方案1】:

    您似乎希望自己验证每个列表值(将其与 0 比较),each_item=True validator 应该适合您

    【讨论】:

    • 我只是简化了示例以删除List。失败与模型与字典表示有关。第一次初始化时,该值是一个模型,但通过 FastAPI 返回时,它只是一个dict,但调用的是同一个验证器。
    • 我认为这是因为您使用的是“pre=True”,导致“其他”字段未正确填充。你可以尝试删除它,看看它是否有效?
    • 删除 pre=True 确实消除了失败。我还有其他问题,但我会开始一个新话题。
    猜你喜欢
    • 2023-01-12
    • 2022-01-15
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2021-03-04
    • 2021-04-04
    • 1970-01-01
    相关资源
    最近更新 更多