【发布时间】:2021-11-04 11:28:51
【问题描述】:
我有一个用例,我想在我的类中创建一些关于模型构造的值。但是,当我在调用 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
控制台输出为:
public_value='hello' secret_value=1
public_value='hello' secret_value=1
但是 Web API 中的 JSON 是:
{
"public_value": "hello",
"secret_value": 2
}
当我单步执行代码时,我可以看到 __init__ 被调用了两次。
先说建设something = SomeModel(public_value="hello")。
第二个出乎我意料的是,在 API 处理程序 exec_test 中调用 return something。
如果这是在类中设置某些内部数据的错误方法,请告诉我正确的使用方法。否则,这似乎是其中一个模块的意外行为。
【问题讨论】: