Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Question] How to use asynccontextmanager #5749

@bldev2473

Description

@bldev2473

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions