pydantic 中是否有任何内置方式来指定选项?例如,假设我想要一个必须具有值“foo”或“bar”的字符串值。
我知道我可以使用正则表达式验证来执行此操作,但是由于我将 pydantic 与 FastAPI 一起使用,因此用户只会将所需的输入视为字符串,但是当他们输入某些内容时,它会给出验证错误。pydantic 的所有内置验证都显示在 api 界面中,所以如果有类似的东西会很棒
class Input(BaseModel):
option: "foo" || "bar"
Run Code Online (Sandbox Code Playgroud)
SCo*_*vin 21
是的,您可以使用枚举:
class Choices(Enum):
foo = 'foo'
bar = 'bar'
class Input(BaseModel):
option: Choices
Run Code Online (Sandbox Code Playgroud)
看这里
或者你可以使用Literal:
class Input(BaseModel):
option: Literal['foo', 'bar']
Run Code Online (Sandbox Code Playgroud)
看这里
想在这里添加另一个选项。您还可以使用正则表达式。对我来说效果更好,因为 Literal 在 python 3.8 之前才可用(不幸的是,这对我来说不是一个容易的升级),而且因为我只期望每个字符串都有一个字符串,所以枚举并不真正适合。
class YourClass(pydantic.BaseModel):
your_attribute: pydantic.constr(regex="^yourvalwith\.escapes\/abcd$")
Run Code Online (Sandbox Code Playgroud)