gpt4 book ai didi

python - 如何验证 pydantic 中的复杂列表类型?

转载 作者:行者123 更新时间:2023-12-02 02:11:19 25 4
gpt4 key购买 nike

为什么 pydantic 不验证 Foo 对象列表的参数,但当参数是基本类型列表时抛出 ValidationError ?

我可以强制执行复杂类型的验证吗?

验证不起作用:

from typing import List
from pydantic import BaseModel


class Foo(BaseModel):
kind: str = "foo"

class Bar(BaseModel):
kind: str = "bar"

class Spam(BaseModel):
foos: List[Foo]

spam = Spam(foos=[Bar()])
print(spam.dict())

>>> {'foos': [{'kind': 'bar'}]}

验证工作:

class Spam(BaseModel):
foos: List[int]


spam = Spam(foos=[Bar()])
print(spam.dict())

pydantic.error_wrappers.ValidationError: 1 validation error for Spam
foos -> 0
value is not a valid integer (type=type_error.integer)

最佳答案

使用pydantic时,应该记住that :

pydantic is primarily a parsing library, not a validation library. Validation is a means to an end: building a model which conforms to the types and constraints provided.

In other words, pydantic guarantees the types and constraints of the output model, not the input data.

为了对传入数据进行额外验证,提供了一个工具 - validators 。例如:

class Spam(BaseModel):
foos: List[Foo]

@validator('foos', pre=True, each_item=True)
def check_squares(cls, v):
assert isinstance(v, Foo), "Foo is only allowed"
return v

关于python - 如何验证 pydantic 中的复杂列表类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67700810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com