1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] FastAPI/Starlette's SessionMiddleware creates new session for every request

Discussão em 'Python' iniciado por Stack, Outubro 8, 2024.

  1. Stack

    Stack Membro Participativo

    I need to create a session for authentication in the session_set endpoint. However, for some reason, the session is still being created in the session_info endpoint. How to make a session created only in session_set? Otherwise, I have a new session in the response with each request.

    Here is my code:

    import uvicorn
    from fastapi import FastAPI, Request
    from starlette.middleware.sessions import SessionMiddleware

    app = FastAPI()
    app.add_middleware(SessionMiddleware, secret_key="some-random-string", max_age=None)


    @app.get("/a")
    async def session_set(request: Request):
    request.session["my_var"] = "1234"
    return 'ok'


    @app.get("/b")
    async def session_info(request: Request):
    my_var = request.session.get("my_var", None)
    return my_var


    if __name__ == '__main__':
    uvicorn.run('http-session:app', port=5000, reload=True)


    [​IMG]

    [​IMG]

    Continue reading...

Compartilhe esta Página