让我们考虑下面的代码
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
对象
我真的不喜欢这种方法,有没有更好的解决办法
目前没有回答
相关问题 更多 >
编程相关推荐