Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Access to main app state from mounted subapp#13908

Discussion options

First Check

  • I added a very descriptive title here.
  • I used the GitHub search to find a similar question and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already searched a privacy-friendly search engine "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but toPydantic.
  • I already checked if it is not related to FastAPI but toSwagger UI.
  • I already checked if it is not related to FastAPI but toReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

fromfastapiimportFastAPIapp=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)

Description

When accessingrequest.app.state from a sub-app path handler, I get the sub-app's state. How do I gain access to the main app's state from the sub-app?

I could of coursesubapp.state.mainstate = app.state but I wonder if there's a better approach?

Operating System

Linux

Operating System Details

Debian unstable

FastAPI Version

0.115.13

Pydantic Version

2.11.5

Python Version

3.13.3

Additional Context

No response

You must be logged in to vote

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

Comment options

You can try many options for it. First one is using middleware:

from fastapi import FastAPI, Requestapp = FastAPI()app.state.foo = "bar"@app.middleware("http")async def attach_parent_state(request: Request, call_next):    request.state.parent_state = app.state    return await call_next(request)@app.get("/app")def read_main(request: Request):    return {"state": request.app.state.foo}subapi = FastAPI()@subapi.get("/sub")def read_sub(request: Request):    parent_state = request.state.parent_state    return {"state": parent_state.foo}app.mount("/subapi", subapi)

Another option, which I like more, is using dependency:

from fastapi import FastAPI, Request, Dependsapp = FastAPI()app.state.foo = "bar"@app.middleware("http")async def attach_parent_state(request: Request, call_next):    request.state.parent_state = app.state    return await call_next(request)@app.get("/app")def read_main(request: Request):    return {"state": request.app.state.foo}subapi = FastAPI()def get_parent_state(request: Request):    return request.app.state.parent_state@subapi.get("/sub")def read_sub(parent_state = Depends(get_parent_state)):    return {"state": parent_state.foo}app.mount("/subapi", subapi)
You must be logged in to vote
3 replies
@madduck
Comment options

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 setsubapi.state.parentstate = api.state, which means this assignment will happen on every request. Is that necessary? The reference toapi.state should not change throughout the programme lifespan, and it seems it should suffice to just assign it once, i.e.

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}

?

@valentinDruzhinin
Comment options

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.

Yours simple and clean example can look like this:

subapi = FastAPI()subapi.parent_state = app.state@subapi.get("/sub")def read_sub(request: Request):    return {"state": request.app.parent_state.foo}
Answer selected byYuriiMotov
@YuriiMotov
Comment options

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)
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Labels
questionQuestion or problem
3 participants
@madduck@valentinDruzhinin@YuriiMotov

[8]ページ先頭

©2009-2025 Movatter.jp