python config_error ai_generated true

AssertionError: SessionMiddleware must be installed to access request.session

ID: python/starlette-session-middleware-missing

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-08-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

Accessing request.session in a Starlette/FastAPI route without adding SessionMiddleware to the app.

generic

中文

在未向应用添加 SessionMiddleware 的情况下,在 Starlette/FastAPI 路由中访问 request.session。

Workarounds

  1. 94% success
    from starlette.middleware.sessions import SessionMiddleware; app.add_middleware(SessionMiddleware, secret_key=SECRET)
  2. 85% success
    Use signed cookies via itsdangerous if you only need one value

Dead Ends

Common approaches that don't work:

  1. 70% fail

    request.state has no session semantics or signing.

  2. 85% fail

    Import alone does not install middleware.