Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork8.3k
Access to main app state from mounted subapp#13908
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
-
First Check
Commit to Help
Example CodefromfastapiimportFastAPIapp=FastAPI()app.state.foo="bar"@app.get("/app")defread_main(request):return {"state":request.app.state.foo}subapi=FastAPI()@subapi.get("/sub")defread_sub(request):return {"state":request.app.state.foo}app.mount("/subapi",subapi) DescriptionWhen accessing I could of course Operating SystemLinux Operating System DetailsDebian unstable FastAPI Version0.115.13 Pydantic Version2.11.5 Python Version3.13.3 Additional ContextNo response |
BetaWas this translation helpful?Give feedback.
All reactions
You're right. Assigningsubapi.parent_state = app.state once before mounting is enough (no need for middleware) sinceapp.state is stable during app lifespan. That was presented just as an example. if you have dynamic per-request data.
Usingrequest.app.parent_state.foo is cleaner and simpler for static shared state than usingrequest.state. Middleware is better if you have per-request dynamic context, not static per-app data. So this was an example too, because you asked for some other options :)
I prefer to use DI, because it's dynamic, it's easier to mock for testing (because it's not global), and it makes handlers more clean, because you don't rely on fields somewhere deeply in app.
Y…
Replies: 1 comment 3 replies
-
You can try many options for it. First one is using middleware: Another option, which I like more, is using dependency: |
BetaWas this translation helpful?Give feedback.
All reactions
-
Ah, dependencies, of course! Thank you@valentinDruzhinin! I have yet to learn the art of DI, but this will be a good starting point. One question I have about your examples though: you use middleware to set subapi=FastAPI()subapi.state.parentstate=api.state And the next question I have is: What is the benefit of your second example in code, over just: @subapi.get("/sub")defread_sub(request:Request):return {"state":request.app.parent_state.foo} ? |
BetaWas this translation helpful?Give feedback.
All reactions
-
You're right. Assigning Using Yours simple and clean example can look like this: |
BetaWas this translation helpful?Give feedback.
All reactions
-
Or, using lifespan: fromfastapiimportDepends,FastAPI,Requestasyncdeflifespan(app:FastAPI):yield {"root_app":app}app=FastAPI(lifespan=lifespan)app.state.foo="bar"@app.get("/app")defread_main(request:Request):return {"state":request.state.root_app.state.foo}subapi=FastAPI()defget_parent_state(request:Request):returnrequest.state.root_app.state@subapi.get("/sub")defread_sub(parent_state=Depends(get_parent_state)):return {"state":parent_state.foo}app.mount("/subapi",subapi) |
BetaWas this translation helpful?Give feedback.