reflex icon indicating copy to clipboard operation
reflex copied to clipboard

[Question] How to use asynccontextmanager

Open bldev2473 opened this issue 4 months ago β€’ 1 comments

I am trying to globally initialize a DB instance using asynccontextmanager in my FastAPI backend server and access it during API requests. When I run the Reflex app, the lifespan code executes, but the value is not stored in the request's state. Is there a different way to execute the code correctly?

app.py

from app.backend import fastapi_app
from app.backend import lifespan

app = rx.App(
    api_transformer=fastapi_app, 
)

app.register_lifespan_task(lifespan)

backend.py

@asynccontextmanager
async def lifespan(app: FastAPI):
    # app startup
    app.state.db = get_firestore_client()

    yield

    # app teardown
    pass

fastapi_app = FastAPI(
    lifespan=lifespan
)
...

@fastapi_app.get("/api/posts/{post_id}")
async def get_post(
    post_id: str,
    request: Request,
):
    # AttributeError: 'State' object has no attribute 'db'
    client = request.app.state.db
...

bldev2473 avatar Sep 01 '25 09:09 bldev2473

generally speaking only the outer-most ASGI app runs the lifespan. So in your case, app in the lifespan is Reflex's outer Starlette app, not your FastAPI app.

as a workaround you can probably look through the starlette mounts, find the FastAPI instance, and assign your db to that.

masenf avatar Oct 30 '25 00:10 masenf