3

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)

enter image description here

enter image description here

Chris
  • 18,724
  • 6
  • 46
  • 80
28 Lucky
  • 43
  • 1
  • 5

1 Answers1

3

You could use a Middleware to override the session value in the Response cookies (check the documentation in Starlette as well) every time a new request arrives; hence, the session will remain the same.

Note: Remember to declare your custom middleware, after adding the SessionMiddleware to the app instance, as the order that endpoints/sub-applications are defined in your application matters, as described in this answer (see the relevant FastAPI documentation as well).

Working Example:

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

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

@app.middleware("http")
async def some_middleware(request: Request, call_next):
    response = await call_next(request)
    session = request.cookies.get('session')
    if session:
        response.set_cookie(key='session', value=request.cookies.get('session'), httponly=True)
    return response
 
@app.get("/a")
def func_a(request: Request):
    request.session["my_var"] = "1234"
    print(request.cookies.get('session'))
    return 'OK'

@app.get("/b")
def func_b(request: Request):
    my_var = request.session.get("my_var", None)
    print(request.cookies.get('session'))
    return my_var
Chris
  • 18,724
  • 6
  • 46
  • 80
  • Can i do sessions in fastapi like this https://prnt.sc/klQyAwad0iKb ? Without set-cookie in response headers. Or this impossible? – 28 Lucky Oct 03 '22 at 20:52