【问题标题】:How to toggle boolean value in Pydantic (FastAPI)如何在 Pydantic (FastAPI) 中切换布尔值
【发布时间】:2021-04-26 10:36:46
【问题描述】:

编辑:在@juanpa.arrivillaga 正确辩称最初的问题没有提供最小可复制示例后,我决定重写它添加更多上下文:我正在使用 FastAPI。

我试图通过定义一个将返回项目值的not 的验证器来调整项目值:

from pydantic import BaseModel, Field, validator


class Foo(BaseModel):
    key: str = Field(...)
    condition: bool = Field(...)

    @validator('condition')
    def toogleCondition(cls, v):
        return not v

这个工具有效

但是,在 FastAPI 中使用该模型时(显然)不起作用。

from fastapi import FastAPI
from pydantic import BaseModel, Field, validator


# insert Foo definition here

app = FastAPI()


@app.get("/fail", response_model=Foo)
def fail():
    return Foo(key='hola', condition=True)


@app.get("/success")
def success():
    return Foo(key='hola', condition=True).dict()

如果您运行该代码,您将得到 /fail 将值转换两次,而 /success 仅将其转换一次。

这是因为response_model 再次运行验证,这再次验证了它。

【问题讨论】:

  • 顺便说一句,不要使用 map 来产生副作用......只需使用常规循环。
  • 嗨@juanpa.arrivillaga!你能详细说明一下吗?
  • 这不是minimal reproducible example请提供一个

标签: python python-3.x fastapi pydantic


【解决方案1】:

这通常有效:

>>> import pydantic, typing
>>> data = [{'key': 'foo', 'condition': False}, {'key': 'bar', 'condition': True}]
>>> class Foo(pydantic.BaseModel):
...     key: str
...     condition: bool
...     @pydantic.validator("condition")
...     def toggle_condition(cls, v):
...         return not v
...
>>> class Bar(pydantic.BaseModel):
...     foo_list: typing.List[Foo]
...
>>> Bar(foo_list=data)
Bar(foo_list=[Foo(key='foo', condition=True), Foo(key='bar', condition=False)])
>>> data
[{'key': 'foo', 'condition': False}, {'key': 'bar', 'condition': True}]

这是我正在使用的:

>>> pydantic.version.VERSION
'1.7.3'
>>> import sys
>>> print(sys.version)
3.7.7 (default, May  6 2020, 04:59:01)
[Clang 4.0.1 (tags/RELEASE_401/final)]

【讨论】:

  • :/ 那么我不知道问题出在哪里...我会尝试找到错误,感谢您的时间,不便之处敬请见谅
猜你喜欢
  • 2012-07-21
  • 1970-01-01
  • 2018-05-16
  • 2017-09-27
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 1970-01-01
  • 2021-02-24
相关资源
最近更新 更多