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 ?
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.