Advanced sessions for Starlette and FastAPI frameworks

2.2.1 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

This quickstart demonstrates setting up a basic Starlette application with `starsessions` using the `CookieStore`. It includes `SessionMiddleware` to enable session support and `load_session` to access session data within a view. A `SECRET_KEY` is mandatory for signing session cookies. For local testing, `cookie_https_only` is set to `False` for convenience, but it should be `True` in production for security.

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/

view raw JSON →