Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

request.session in HTTP Middleware #4746

Closed
9 tasks done
sagar-arya opened this issue Mar 31, 2022 · 10 comments
Closed
9 tasks done

request.session in HTTP Middleware #4746

sagar-arya opened this issue Mar 31, 2022 · 10 comments
Labels
question Question or problem question-migrate

Comments

@sagar-arya
Copy link

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware
app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="SECRET_KEY")

@app.middleware("http")
async def validate_user(request: Request, call_next):
    end_point = request.url.path
    request.session["name"] = "some random value"
    response = await call_next(request)
    return response

Description

This is a basic example of my app.
I am trying to add values into the session if the user is valid.
For now, I am trying to set

request.session["name"] = "some random value"

In the process, I get SessionMiddleware must be installed to access request.session

AssertionError: SessionMiddleware must be installed to access request.session

Is there any other way for solving it?
I am able to set it using

request.state.name="some random value"

I am not sure if this is a valid way to do it or not.
Can someone please help me with this?

Operating System

macOS

Operating System Details

No response

FastAPI Version

0.74.1

Python Version

3.10.2

Additional Context

No response

@sagar-arya sagar-arya added the question Question or problem label Mar 31, 2022
@wmcgee3
Copy link

wmcgee3 commented Apr 1, 2022

I was able to find this in the Starlette docs: Session information is readable but not modifiable.
😢

It looks like this package might provide the functionality you're looking for, though!
FastAPI Sessions

@akhilnarang
Copy link

Perhaps you could use this

@sagar-arya
Copy link
Author

I was able to find this in the Starlette docs: Session information is readable but not modifiable. 😢

It looks like this package might provide the functionality you're looking for, though! FastAPI Sessions

@wmcgee3 tried all and going with request.state for now :)
closing the issue

@janczawadzki
Copy link

This may help: order of middleware

@elongstreet88
Copy link

I am still receiving this even just reading the session variable:

@app.middleware("http")
async def validate_user(request: Request, call_next):
    end_point = request.url.path
    print(request.session) # <-- AssertionError: SessionMiddleware must be installed to access request.session
    response = await call_next(request)
    return response

How were you able to end up reading this?

@janczawadzki
Copy link

You need to make sure your middleware is attached to the app FIRST. They are executed in reverse order - what is happening is that session hasn't run yet, so there is no request.session attribute (yet). Get the middleware in the correct order, and you will always run AFTER the session middleware, and the problem goes away.

@elongstreet88
Copy link

@janczawadzki
Thanks for chiming in, as far as i can tell...i'm only using the session middleware and my minimal config looks like this:

from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse, PlainTextResponse
from starlette.middleware.sessions import SessionMiddleware

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

@app.middleware("http")
async def validate_user(request: Request, call_next):
    print(request.session) # <--- Error: 'AssertionError: SessionMiddleware must be installed to access request.session'
    response = await call_next(request)
    return response

@app.get("/set/{item}")
async def set(request: Request, item:str):
    request.session["item"] = item
    return request.session["item"]

@app.get("/get")
async def get(request: Request) -> PlainTextResponse:
    return request.session.get("item", None)

Am i doing something obviously wrong here?
Thanks

@AKrumov
Copy link

AKrumov commented May 30, 2022

@janczawadzki Thanks for chiming in, as far as i can tell...i'm only using the session middleware and my minimal config looks like this:

from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse, PlainTextResponse
from starlette.middleware.sessions import SessionMiddleware

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

@app.middleware("http")
async def validate_user(request: Request, call_next):
    print(request.session) # <--- Error: 'AssertionError: SessionMiddleware must be installed to access request.session'
    response = await call_next(request)
    return response

@app.get("/set/{item}")
async def set(request: Request, item:str):
    request.session["item"] = item
    return request.session["item"]

@app.get("/get")
async def get(request: Request) -> PlainTextResponse:
    return request.session.get("item", None)

Am i doing something obviously wrong here? Thanks

In order to fix this please move: app.add_middleware(SessionMiddleware, secret_key="some-random-string") on the last line. This will fix your problem :)

@elongstreet88
Copy link

HA! That worked but is less than intuitive.... :)
Thanks.

@HarrisonFok
Copy link

@sagar-arya can you post your working code with fastapi-session?

@tiangolo tiangolo reopened this Feb 27, 2023
Repository owner locked and limited conversation to collaborators Feb 27, 2023
@tiangolo tiangolo converted this issue into discussion #6358 Feb 27, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
question Question or problem question-migrate
Projects
None yet
Development

No branches or pull requests

8 participants