FastAPI依赖于用例应用程序

2024-05-06 00:38:03 发布

您现在位置:Python中文网/ 问答频道 /正文

让我们考虑下面的代码

class CommonDependency:
    ...


@app.on_event("startup")
async def start():
    parser = ArgumentParser(...)
    ... # here dep are init with command line arguments
    return dep

@app.get("/")
async def root(dep = Depends(start)):
    ... # here dep is needed
    return ...

start函数需要在启动时运行,因为它将使用命令行参数来创建依赖项

问题是dep是一个有状态的对象,自启动以来,它应该在所有请求中共享它的状态

解决方案是在模块范围内声明dep

dep = CommonDependency(...)

@app.on_event("startup")
async def start():
   dep.property = ... # here the property contains the init dependency that we need

并覆盖类内声明的属性,以便通过所有模块函数访问该属性

但是,这样做,Depends就没有用了,因为所有函数都可以看到dep对象

我真的不喜欢这种方法,有没有更好的解决办法


Tags: 函数eventappasyncreturnhereiniton