Fastapi:如何在路由器中获取应用程序实例?

Fastapi : how to get app instance in router?

我想在我的路由器文件中获取应用程序实例,我应该怎么做?

我的main.py

...
app = FastAPI()
app.machine_learning_model = joblib.load(some_path)
app.include_router(some_router)
...

现在我想在some_router的文件中使用app.machine_learning_model,我该怎么办?

您可以使用 request.app 访问 app 实例,如下所示:

from fastapi import Request

@router.get("/some_route")
async def some_router_function(request: Request):
    model = request.app.machine_learning_model