Advanced sessions for Starlette and FastAPI frameworks
Starsessions provides advanced session management for Starlette and FastAPI applications. It is currently at version 2.2.1 and maintains an active release cadence with regular updates and patches, ensuring compatibility and introducing new features.
Warnings
- breaking Version 2.0.0 introduced significant breaking changes, most notably renaming session 'Backends' to 'Stores' (e.g., `CookieBackend` became `CookieStore`, `RedisBackend` became `RedisStore`). The `Session` class was also removed, and method signatures (like `Store.write`) were altered. Middleware argument names were also changed.
- breaking Python 3.6 support was dropped in `starsessions` v2.0.0.
- gotcha By default, `starsessions` does not autoload session data for performance reasons. You must explicitly call `await load_session(request)` in your endpoint or middleware before accessing `request.session`, or use `SessionAutoloadMiddleware`. Failure to do so will result in an empty session or `SessionNotLoaded` errors.
- gotcha When using `CookieStore`, session data is signed to prevent tampering but is NOT encrypted by default. This means sensitive information stored in the session cookie can be read by the client. For confidentiality, you must provide an `Encryptor` (e.g., `FernetEncryptor`) to the `SessionMiddleware`.
- gotcha When using `RedisStore`, you must explicitly close the Redis connection when the application shuts down. The library does not handle this automatically. The recommended approach is to use a lifespan handler in your ASGI application.
- gotcha The order of middleware in Starlette/FastAPI applications is crucial. If `SessionMiddleware` or `SessionAutoloadMiddleware` is placed incorrectly relative to other middlewares that modify the request or response, unexpected behavior or session issues may arise.
- gotcha Default cookie security settings (`cookie_https_only=True`, `cookie_same_site='strict'`) can cause issues in cross-domain or HTTP development environments. While secure by default, these might prevent cookies from being set or sent by the browser in certain scenarios.
Install
-
pip install starsessions -
pip install starsessions[redis] -
pip install starsessions[cryptography]
Imports
- SessionMiddleware
from starsessions import SessionMiddleware
- CookieStore
from starsessions import CookieStore
- InMemoryStore
from starsessions import InMemoryStore
- load_session
from starsessions import load_session
- RedisStore
from starsessions.stores.redis import RedisStore
- FernetEncryptor
from starsessions.encryptors import FernetEncryptor
Quickstart
import os
import uvicorn
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.responses import JSONResponse
from starlette.routing import Route
from starsessions import SessionMiddleware, CookieStore, load_session
# It's crucial to use a strong, randomly generated secret key in production.
# For local development, you might use a placeholder, but fetch from env vars.
SECRET_KEY = os.environ.get("SESSION_SECRET_KEY", "a-very-secret-key-that-you-should-change")
session_store = CookieStore(secret_key=SECRET_KEY)
async def homepage(request):
await load_session(request)
if "counter" not in request.session:
request.session["counter"] = 0
request.session["counter"] += 1
return JSONResponse({"message": "Session accessed!", "counter": request.session["counter"]})
routes = [
Route("/", homepage),
]
middleware = [
Middleware(SessionMiddleware, store=session_store, lifetime=3600 * 24 * 7, cookie_https_only=False)
]
app = Starlette(routes=routes, middleware=middleware)
# To run this example:
# 1. Save as e.g., `app.py`
# 2. `pip install starlette uvicorn starsessions`
# 3. `uvicorn app:app --reload`
# 4. Access at http://127.0.0.1:8000/