FastAPI - 如何在路由器内获取应用程序实例?

发布于 2025-01-10 14:44:03 字数 293 浏览 0 评论 0 原文

我想在我的路由器文件中获取 app 实例,我该怎么办?

我的main.py如下:

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

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

I want to get the app instance in my router file, what should I do ?

My main.py is as follows:

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

Now I want to use app.machine_learning_model in some_router's file , what should I do ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

离笑几人歌 2025-01-17 14:44:03

因为 FastAPI 实际上是 Starlette 底层,您可以使用通用 app.state 属性将模型存储在应用程序实例上,如 Starlette 的 文档(请参阅 State 类实现也是如此)。示例:

app.state.ml_model = joblib.load(some_path)

对于从主文件外部访问 app 实例(以及随后的模型),您可以使用 Request 对象。根据 Starlette 的文档,其中请求 可用(即端点和中间件),apprequest.app 上可用。示例:

from fastapi import Request

@router.get('/')
def some_router_function(request: Request):
    model = request.app.state.ml_model

或者,现在可以使用 request.state 来存储全局变量/对象,方法是在 lifespan 处理程序中初始化它们,如中所述这个答案

Since FastAPI is actually Starlette underneath, you could store the model on the application instance using the generic app.state attribute, as described in Starlette's documentation (see State class implementation too). Example:

app.state.ml_model = joblib.load(some_path)

As for accessing the app instance (and subsequently, the model) from outside the main file, you can use the Request object. As per Starlette's documentation, where a request is available (i.e., endpoints and middleware), the app is available on request.app. Example:

from fastapi import Request

@router.get('/')
def some_router_function(request: Request):
    model = request.app.state.ml_model

Alternatively, one could now use request.state to store global variables/objects, by initializing them within the lifespan handler, as explained in this answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文