小编Rya*_*oss的帖子

为什么 FastAPI 从路由函数返回时会执行 Pydantic 构造函数两次?

我有一个用例,我想在构建模型的类中创建一些值。但是,当我在调用 API 时将类返回到 FastAPI 以便转换为 JSON 时,构造函数会再次运行,并且我可以获得与原始实例不同的值。

这是一个人为的例子来说明:

class SomeModel(BaseModel):
    public_value: str
    secret_value: Optional[str]

    def __init__(self, **data):
        super().__init__(**data)
        # this could also be done with default_factory
        self.secret_value = randint(1, 5)


def some_function() -> SomeModel:
    something = SomeModel(public_value="hello")
    print(something)
    return something


@app.get("/test", response_model=SomeModel)
async def exec_test():
    something = some_function()
    print(something)
    return something
Run Code Online (Sandbox Code Playgroud)

控制台输出为:

public_value='hello' secret_value=1
public_value='hello' secret_value=1
Run Code Online (Sandbox Code Playgroud)

但 Web API 中的 JSON 是:

{
  "public_value": "hello",
  "secret_value": 2
}
Run Code Online (Sandbox Code Playgroud)

当我单步执行代码时,我可以看到__init__被调用两次。

首先是在建设上something = SomeModel(public_value="hello")

其次,令我意想不到的是,在调用的 API 处理程序exec_test …

python pydantic fastapi

8
推荐指数
2
解决办法
2792
查看次数

标签 统计

fastapi ×1

pydantic ×1

python ×1