Install & Compatibility
Where this runs
tested against v2.2.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.960 runs
installs and imports cleanly · install 0.0s · import 0.330s · 25.5MB
glibcpy 3.10–3.960 runs
installs and imports cleanly · install 2.1s · import 0.300s · 26MB
24MB installed
● package 24MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
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
✗ from starsessions import RedisStore
RedisStore is located in a submodule and requires `starsessions[redis]` to be installed.
FernetEncryptor
✓ from starsessions.encryptors import FernetEncryptor
✗ from starsessions import FernetEncryptor
FernetEncryptor is located in a submodule and requires `starsessions[cryptography]` to be installed.
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/
Debug
Known issues
breakingVersion 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.fixUpdate your code to use `*Store` classes instead of `*Backend` classes, remove direct `Session` class usage, and review method signatures and middleware argument names against the v2.0.0+ documentation.
affects: >=2.0.0
breakingPython 3.6 support was dropped in `starsessions` v2.0.0.fixEnsure your project is running on Python 3.8 or newer to use `starsessions` v2.0.0 and above.
affects: >=2.0.0
gotchaBy 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.fixAdd `await load_session(request)` at the beginning of any view or middleware that needs to interact with the session, or configure `SessionAutoloadMiddleware` in your application's middleware stack.
affects: All versions
gotchaWhen 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`.fixImport `FernetEncryptor` from `starsessions.encryptors` and pass an instance to `SessionMiddleware` via the `encryptor` argument, ensuring `starsessions[cryptography]` is installed.
affects: All versions
gotchaWhen 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.fixImplement an ASGI lifespan handler to properly initialize and `aclose()` your `redis.asyncio.Redis` client when your application starts and stops.
affects: All versions using RedisStore
gotchaThe 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.fixEnsure `SessionMiddleware` is placed appropriately in your middleware stack, typically before any middleware or route handlers that need to access or modify the session.
affects: All versions
gotchaDefault 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.fixFor development, you might set `cookie_https_only=False` and `cookie_same_site='lax'`. For cross-domain production deployments, carefully configure `cookie_same_site='none'` along with `cookie_https_only=True` and ensure your frontend handles `withCredentials`.
affects: All versions
Errors
Common errors & fixes
ImportError: cannot import name 'SessionMiddleware' from 'starsessions'
The `SessionMiddleware` class is located in the `starsessions.middleware` submodule, not directly available under the top-level `starsessions` package.
fixfrom starsessions.middleware import SessionMiddleware
TypeError: SessionMiddleware.__init__() missing 1 required positional argument: 'secret_key'
The `SessionMiddleware` requires a `secret_key` (a strong, randomly generated string) for session encryption and signing, which was not provided during initialization.
fixapp.add_middleware(SessionMiddleware, backend=backend, secret_key="your_secure_secret_key_here")
AttributeError: 'Request' object has no attribute 'session'
The `SessionMiddleware` was not correctly added to your Starlette or FastAPI application's middleware stack, or it failed to initialize, preventing the `request.session` object from being injected.
fixfrom starlette.applications import Starlette
from starsessions.middleware import SessionMiddleware
from starsessions.backends.memory import MemoryBackend
app = Starlette()
backend = MemoryBackend()
app.add_middleware(SessionMiddleware, backend=backend, secret_key="your_secure_secret_key_here")
# ... your routes and handlers where request.session is accessed
Upgrade
Version history
2.2.1latest on PyPI · released Oct 23, 2024
Audit
Dependencies
starletterequiredCore ASGI framework integration.
itsdangerousrequiredUsed for signing session data, especially with CookieStore.
redisoptionalRequired for RedisStore functionality. Install with `starsessions[redis]`.
cryptographyoptionalRequired for encryption, e.g., using FernetEncryptor with CookieStore. Install with `starsessions[cryptography]`.