question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

request.session in HTTP Middleware

See original GitHub issue

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

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:9

github_iconTop GitHub Comments

1reaction
elongstreet88commented, Jun 1, 2022

HA! That worked but is less than intuitive… 😃 Thanks.

1reaction
AKrumovcommented, 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 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Express session middleware
To store or access session data, simply use the request property req.session , which is (generally) serialized as JSON by the store, so...
Read more >
Sessions - Pode - Read the Docs
Session Middleware is supported on web requests and responses in the form of signed a cookie/header and server-side data storage. When configured the...
Read more >
How to use sessions - Django documentation
Sessions are implemented via a piece of middleware. To enable session functionality, do the following: Edit the MIDDLEWARE setting and make sure it...
Read more >
Creating middleware for all requests and setting session ...
Place your middleware class name after \Illuminate\Session\Middleware\StartSession . Then you willable to call $request->session(); in your ...
Read more >
ring.middleware.session documentation
Reads in the current HTTP session map, and adds it to the :session key on the request. If a :session key is added...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found