让我们考虑以下代码
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
对象对所有函数都是可见的。
我真的不喜欢这种方法,有没有更好的解决方案?