I want to get the app
instance in my router file, what should I do ?
My main.py
is as follows:
JavaScript
x
6
1
# ...
2
app = FastAPI()
3
app.machine_learning_model = joblib.load(some_path)
4
app.include_router(some_router)
5
# ...
6
Now I want to use app.machine_learning_model
in some_router’s file , what should I do ?
Advertisement
Answer
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):
JavaScript
1
2
1
app.state.ml_model = joblib.load(some_path)
2
As for accessing the app
instance (and subsequently, the model) from outside the main file—as per the documentation, where a request
is available (i.e., endpoints and middleware), the app
is available on request.app
. Example:
JavaScript
1
6
1
from fastapi import Request
2
3
@router.get("/some_route")
4
def some_router_function(request: Request):
5
model = request.app.state.ml_model
6