[Python] FastAPI state not isolated between concurrent users

Discussão em 'Python' iniciado por Stack, Junho 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have a FastAPI app. In main.py:

    @asynccontextmanager
    async def lifespan(app: FastAPI):
    # Setup
    app.state.session_store = {}
    yield


    In another file, I have the following function:

    def get_user_state(request: Request, response: Response) -> AppState:
    logger.debug("Session state called")
    session_store = request.app.state.session_store
    logger.debug(f"Session store: {session_store}")
    session_id = request.headers.get("user-id")
    if session_id not in session_store:
    session_store[session_id] = AppState()
    return session_store[session_id]


    It gets called with:

    @router.post("/endpoint")
    async def my_function(
    body: MyRequest,
    request: Request,
    response: Response,
    user_state: AppState = Depends(get_user_state)
    ):


    If two instances are running with different user_id values, I can see that the session_store has two different AppState() objects. However, if I add a variable to one of them, it gets added to both. Why??

    Continue reading...

Compartilhe esta Página