简体   繁体   中英

FastAPI - How to get app instance inside a router?

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?

You should store the model on the app instance using the generic app.state attribute, as described in the documentation (see State class implementation too):

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

As for accessing the app instance (and subsequently, the model) from outside the main file—as per the documentation , where a request is available (ie, endpoints and middleware), the app is available on request.app . Example:

from fastapi import Request

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM