我有一个用例,我想在构建模型的类中创建一些值。但是,当我在调用 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 …