### Run ASGI Application Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Start the application using the Uvicorn server. ```python if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) ``` -------------------------------- ### Install Starsessions Package Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Install the core starsessions package using pip. ```bash pip install starsessions ``` -------------------------------- ### Install Starsessions with Redis Support Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Install the starsessions package with the 'redis' extra for Redis support. ```bash pip install starsessions[redis] ``` -------------------------------- ### Integrate Starsessions with FastAPI Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Example setup for using Starsessions middleware within a FastAPI application. ```python import datetime from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, RedirectResponse from starsessions import ( CookieStore, SessionAutoloadMiddleware, SessionMiddleware, regenerate_session_id, ) app = FastAPI() ``` -------------------------------- ### Configure Cookie Security Options Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Customize cookie security settings like HTTPS enforcement, same-site policy, and lifetime. This example relaxes HTTPS enforcement and sets a 14-day lifetime. ```python from starlette.middleware import Middleware from starsessions import CookieStore, SessionMiddleware session_store = CookieStore(secret_key='TOP SECRET') middleware = [ Middleware( SessionMiddleware, store=session_store, cookie_https_only=False, cookie_same_site='lax', lifetime=3600 * 24 * 14, ), ] ``` -------------------------------- ### Initialize RedisStore Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Connect to a Redis server for session storage, ensuring the connection is closed on application shutdown. ```python from redis.asyncio import Redis from starsessions.stores.redis import RedisStore client = Redis.from_url('redis://localhost') store = RedisStore(connection=client) # close connection on shutdown await client.aclose() ``` -------------------------------- ### Configure CookieStore Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Implements client-side session storage using signed cookies. Encryption is optional but recommended for sensitive data. ```python from starlette.middleware import Middleware from cryptography.fernet import Fernet from starsessions import CookieStore, SessionMiddleware from starsessions.encryptors import FernetEncryptor # Basic usage - data is signed but NOT encrypted (visible to users) basic_store = CookieStore(secret_key="your-secret-key") # With encryption for sensitive data encryption_key = Fernet.generate_key() # Store securely in env var encryptor = FernetEncryptor(encryption_key) middleware = [ Middleware( SessionMiddleware, store=CookieStore(secret_key="signing-key", max_size=4096), encryptor=encryptor, # Now session data is encrypted lifetime=3600, ), ] ``` -------------------------------- ### Lint and Format Code with Ruff Source: https://github.com/alex-oleshkevich/starsessions/blob/master/AGENTS.md Use `uv` and `ruff` to check for code style issues and format the code. ```bash uv run ruff check starsessions tests ``` ```bash uv run ruff format starsessions tests ``` -------------------------------- ### Manual Session Loading Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Demonstrates explicit session loading and handling of the SessionNotLoaded exception. ```python from starlette.requests import Request from starlette.responses import JSONResponse from starsessions import load_session, SessionNotLoaded async def view_with_session(request: Request) -> JSONResponse: # Load session data from storage await load_session(request) # Now safe to access session request.session["key"] = "value" data = request.session.get("key", "default") return JSONResponse({"data": data}) async def view_without_load(request: Request) -> JSONResponse: # This will raise SessionNotLoaded exception try: request.session["key"] = "value" except SessionNotLoaded as e: return JSONResponse({"error": str(e)}, status_code=500) ``` -------------------------------- ### Session Autoloading Middleware with Regex Paths Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Use regular expressions with SessionAutoloadMiddleware to define more complex path matching for session autoloading. ```python import re from starlette.middleware import Middleware from starsessions import CookieStore, SessionAutoloadMiddleware, SessionMiddleware session_store = CookieStore(secret_key='TOP SECRET') middleware = [ Middleware(SessionMiddleware, store=session_store), Middleware(SessionAutoloadMiddleware, paths=[re.compile(r'/admin.*')]) ] ``` -------------------------------- ### Implement a Custom Session Store Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Extends SessionStore to create a custom backend, requiring implementation of read, write, and remove methods. ```python from starsessions import SessionStore class InMemoryStore(SessionStore): def __init__(self) -> None: self._storage: dict[str, bytes] = {} async def read(self, session_id: str, lifetime: int) -> bytes: """Read session data from a data source using session_id.""" return self._storage.get(session_id, b"") async def write(self, session_id: str, data: bytes, lifetime: int, ttl: int) -> str: """Write session data into the data source and return session ID.""" self._storage[session_id] = data return session_id async def remove(self, session_id: str) -> None: """Remove session data.""" self._storage.pop(session_id, None) ``` -------------------------------- ### Basic Starlette App with Session Middleware Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Integrate SessionMiddleware into a Starlette application using CookieStore. Ensure session data is loaded before access. ```python from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.responses import JSONResponse from starlette.routing import Route from starsessions import CookieStore, load_session, SessionMiddleware async def index_view(request): await load_session(request) session_data = request.session return JSONResponse(session_data) session_store = CookieStore(secret_key='TOP SECRET') app = Starlette( middleware=[ Middleware(SessionMiddleware, store=session_store, lifetime=3600 * 24 * 14), ], routes=[ Route('/', index_view), ] ) ``` -------------------------------- ### Configure Lifespan and Session Middleware Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Sets up a Starlette application with a lifespan handler for connection management and session middleware for data persistence. ```python @contextlib.asynccontextmanager async def lifespan(app: Starlette) -> typing.AsyncGenerator[dict, None]: async with redis_client: yield {} async def view(request: Request) -> JSONResponse: request.session["data"] = "stored in redis" return JSONResponse(request.session) app = Starlette( middleware=[ Middleware(SessionMiddleware, store=store, lifetime=3600, rolling=True), Middleware(SessionAutoloadMiddleware), ], routes=[Route("/", view)], lifespan=lifespan, ) ``` -------------------------------- ### Implement Custom Serializers Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Create custom serialization formats by extending the Serializer base class. Useful for formats like Pickle or MessagePack. ```python import pickle from starsessions import Serializer class PickleSerializer(Serializer): def serialize(self, data: object) -> bytes: """Serialize session data to bytes.""" return pickle.dumps(data) def deserialize(self, data: bytes) -> dict: """Deserialize bytes back to session data.""" if not data: return {} return pickle.loads(data) # Usage with MessagePack (requires msgpack package) import msgpack class MsgPackSerializer(Serializer): def serialize(self, data: object) -> bytes: return msgpack.packb(data, use_bin_type=True) def deserialize(self, data: bytes) -> dict: if not data: return {} return msgpack.unpackb(data, raw=False) ``` -------------------------------- ### Configure encrypted CookieStore Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Use an encryptor with CookieStore to protect sensitive session data from being read in plaintext. ```python from cryptography.fernet import Fernet from starsessions.encryptors import FernetEncryptor key = Fernet.generate_key() # store this securely, e.g. in an env var encryptor = FernetEncryptor(key) middleware = [ Middleware( SessionMiddleware, store=CookieStore(secret_key="..."), encryptor=encryptor, ) ] ``` -------------------------------- ### Configure SessionMiddleware Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Integrates session support into a Starlette application using a cookie-based store. ```python from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.requests import Request from starlette.responses import JSONResponse from starlette.routing import Route from starsessions import CookieStore, SessionMiddleware, load_session async def index_view(request: Request) -> JSONResponse: await load_session(request) request.session["visits"] = request.session.get("visits", 0) + 1 return JSONResponse({"visits": request.session["visits"]}) session_store = CookieStore(secret_key="your-secret-key-here") app = Starlette( middleware=[ Middleware( SessionMiddleware, store=session_store, lifetime=3600 * 24 * 14, # 14 days cookie_name="session", cookie_same_site="lax", cookie_https_only=True, cookie_domain=None, cookie_path=None, rolling=False, ), ], routes=[Route("/", index_view)], ) ``` -------------------------------- ### Configure FernetEncryptor Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Uses Fernet encryption for session data, supporting key rotation via MultiFernet. ```python from cryptography.fernet import Fernet, MultiFernet from starlette.middleware import Middleware from starsessions import CookieStore, SessionMiddleware from starsessions.encryptors import FernetEncryptor # Generate a new key (do this once and store securely) key = Fernet.generate_key() print(f"Store this key securely: {key.decode()}") # Basic usage encryptor = FernetEncryptor(key) # Key rotation with MultiFernet - new key first, then old keys new_key = Fernet.generate_key() old_key = key multi_fernet = MultiFernet([Fernet(new_key), Fernet(old_key)]) # Use MultiFernet directly if needed for rotation # encryptor_with_rotation = FernetEncryptor(new_key) middleware = [ Middleware( SessionMiddleware, store=CookieStore(secret_key="signing-secret"), encryptor=encryptor, lifetime=3600 * 24, ), ] ``` -------------------------------- ### Configure InMemoryStore Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Stores session data in process memory, making it suitable only for development and testing. Data is lost upon server restart. ```python from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.requests import Request from starlette.responses import JSONResponse from starlette.routing import Route from starsessions import InMemoryStore, SessionMiddleware, load_session async def counter(request: Request) -> JSONResponse: await load_session(request) request.session["count"] = request.session.get("count", 0) + 1 return JSONResponse({"count": request.session["count"]}) # gc_ttl sets how long to keep session data for session-only cookies memory_store = InMemoryStore(gc_ttl=3600 * 24) # 24 hours default app = Starlette( middleware=[ Middleware(SessionMiddleware, store=memory_store, lifetime=3600), ], routes=[Route("/", counter)], ) ``` -------------------------------- ### Access Session Utility Functions Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Use helper functions to inspect session state, metadata, and remaining lifetime for debugging or activity tracking. ```python from starlette.requests import Request from starlette.responses import JSONResponse from starsessions import ( load_session, is_loaded, get_session_id, get_session_handler, get_session_metadata, get_session_remaining_seconds, ) async def session_info(request: Request) -> JSONResponse: # Check if session is already loaded if not is_loaded(request): await load_session(request) # Get current session ID (None if new session) session_id = get_session_id(request) # Get session metadata metadata = get_session_metadata(request) # Get remaining time before expiration remaining = get_session_remaining_seconds(request) # Access low-level session handler handler = get_session_handler(request) return JSONResponse({ "session_id": session_id, "is_loaded": is_loaded(request), "is_empty": handler.is_empty, "initially_empty": handler.initially_empty, "lifetime": metadata["lifetime"], "created": metadata["created"], "last_access": metadata["last_access"], "remaining_seconds": remaining, }) ``` -------------------------------- ### Configure RedisStore Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Persists session data in Redis for production environments. Supports custom key prefixes and TTL-based expiration. ```python import contextlib import typing from redis.asyncio import Redis from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.requests import Request from starlette.responses import JSONResponse from starlette.routing import Route from starsessions import SessionAutoloadMiddleware, SessionMiddleware from starsessions.stores.redis import RedisStore # Create Redis client redis_client = Redis.from_url("redis://localhost:6379/0") # Create store with custom prefix and gc_ttl store = RedisStore( connection=redis_client, prefix="myapp.sessions.", # Keys will be: myapp.sessions. gc_ttl=3600 * 24 * 30, # 30 days for session-only cookies ) # Custom prefix function def custom_prefix(session_id: str) -> str: return f"user_sessions:{session_id}" store_with_callable_prefix = RedisStore(connection=redis_client, prefix=custom_prefix) ``` -------------------------------- ### Configure Starsessions Middleware Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Register the autoload and session middlewares with the application instance. ```python app.add_middleware(SessionAutoloadMiddleware) app.add_middleware( SessionMiddleware, store=CookieStore(secret_key="your-secret-key"), lifetime=3600 * 24, # 24 hours cookie_https_only=False, # Set True in production cookie_same_site="lax", ) ``` -------------------------------- ### Session Autoloading Middleware (Always) Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Configure SessionAutoloadMiddleware to automatically load the session for every request. Requires SessionMiddleware to be present. ```python from starlette.middleware import Middleware from starsessions import CookieStore, SessionAutoloadMiddleware, SessionMiddleware session_store = CookieStore(secret_key='TOP SECRET') # Always autoload middleware = [ Middleware(SessionMiddleware, store=session_store), Middleware(SessionAutoloadMiddleware), ] ``` -------------------------------- ### Configure AESGCMEncryptor Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Implements authenticated encryption using AES-256-GCM with a 32-byte key. ```python import os from starlette.middleware import Middleware from starsessions import CookieStore, SessionMiddleware from starsessions.encryptors import AESGCMEncryptor # Generate a 256-bit key (do this once and store securely) key = os.urandom(32) encryptor = AESGCMEncryptor(key) middleware = [ Middleware( SessionMiddleware, store=CookieStore(secret_key="signing-secret"), encryptor=encryptor, lifetime=3600, ), ] ``` -------------------------------- ### Configure SessionAutoloadMiddleware Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Automatically loads sessions for specific URL patterns, removing the need for manual loading. ```python import re from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.requests import Request from starlette.responses import JSONResponse from starlette.routing import Route from starsessions import CookieStore, SessionAutoloadMiddleware, SessionMiddleware async def dashboard(request: Request) -> JSONResponse: # Session is already loaded - no need to call load_session() return JSONResponse({"user": request.session.get("user")}) async def public_page(request: Request) -> JSONResponse: return JSONResponse({"message": "Public content"}) app = Starlette( middleware=[ # SessionMiddleware must come before SessionAutoloadMiddleware Middleware(SessionMiddleware, store=CookieStore(secret_key="secret")), # Autoload sessions only for /admin and /dashboard paths Middleware(SessionAutoloadMiddleware, paths=["/admin", "/dashboard", re.compile(r"/api/.*")]), ], routes=[ Route("/dashboard", dashboard), Route("/public", public_page), ], ) ``` -------------------------------- ### Session Autoloading Middleware (Specific Paths) Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Configure SessionAutoloadMiddleware to only autoload sessions for a specified list of paths. This reduces overhead by only loading sessions when needed. ```python from starlette.middleware import Middleware from starsessions import CookieStore, SessionAutoloadMiddleware, SessionMiddleware session_store = CookieStore(secret_key='TOP SECRET') # Autoload for selected paths only middleware = [ Middleware(SessionMiddleware, store=session_store), Middleware(SessionAutoloadMiddleware, paths=['/admin', '/app']), ] ``` -------------------------------- ### Configure Fernet Encryption Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Uses Fernet for session encryption, which is recommended for its simplicity and key rotation support. ```python from cryptography.fernet import Fernet from starlette.middleware import Middleware from starsessions import CookieStore, SessionMiddleware from starsessions.encryptors import FernetEncryptor # generate once and store securely (e.g. ENCRYPTION_KEY env var). # rotating keys: pass a MultiFernet instance wrapping old + new keys. key = Fernet.generate_key() middleware = [ Middleware( SessionMiddleware, store=CookieStore(secret_key="..."), encryptor=FernetEncryptor(key), ) ] ``` -------------------------------- ### Configure Rolling Sessions Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Enable rolling sessions by setting rolling=True to extend session expiration on every request. ```python from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.requests import Request from starlette.responses import JSONResponse from starlette.routing import Route from starsessions import CookieStore, SessionAutoloadMiddleware, SessionMiddleware async def activity(request: Request) -> JSONResponse: # Each request extends the session by 300 seconds request.session["last_activity"] = "now" return JSONResponse({"status": "active"}) middleware = [ Middleware( SessionMiddleware, store=CookieStore(secret_key="secret"), lifetime=300, # 5 minutes rolling=True, # Extend on each request cookie_https_only=False, ), Middleware(SessionAutoloadMiddleware), ] app = Starlette( middleware=middleware, routes=[Route("/", activity)], ) ``` -------------------------------- ### Run All Tests with Uvicorn Source: https://github.com/alex-oleshkevich/starsessions/blob/master/AGENTS.md Execute all tests in the project using the `uv` command with `pytest`. ```bash uv run pytest ``` -------------------------------- ### Implement a Custom Serializer Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Allows defining custom serialization formats by implementing the Serializer abstract class. ```python import json from starlette.middleware import Middleware from starsessions import Serializer, SessionMiddleware class MySerializer(Serializer): def serialize(self, data: object) -> bytes: return json.dumps(data).encode('utf-8') def deserialize(self, data: bytes) -> dict[str, object]: return json.loads(data) middleware = [ Middleware(SessionMiddleware, serializer=MySerializer()), ] ``` -------------------------------- ### Configure Redis Store with TTL Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Sets a custom garbage collection TTL for Redis sessions, useful when session-only cookies are used. ```python from redis.asyncio import Redis from starsessions.stores.redis import RedisStore client = Redis.from_url('redis://localhost') store = RedisStore(connection=client, gc_ttl=3600) # max 1 hour ``` -------------------------------- ### Implement Custom Encryptor Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Creates a custom encryption scheme by extending the Encryptor base class and implementing encrypt and decrypt methods. ```python from starsessions.encryptors import Encryptor class CustomEncryptor(Encryptor): def __init__(self, key: bytes) -> None: self.key = key def encrypt(self, data: bytes) -> bytes: """Encrypt session data before storage.""" # Implement your encryption logic # Example using a hypothetical encryption library import hypothetical_crypto return hypothetical_crypto.encrypt(data, self.key) def decrypt(self, data: bytes) -> bytes: """Decrypt session data after retrieval.""" import hypothetical_crypto return hypothetical_crypto.decrypt(data, self.key) ``` -------------------------------- ### Configure Session Lifetime with Timedelta Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Set the session lifetime using a datetime.timedelta object for more precise control. ```python import datetime from starlette.middleware import Middleware from starsessions import SessionMiddleware middleware = [ Middleware(SessionMiddleware, lifetime=datetime.timedelta(days=14)), ] ``` -------------------------------- ### Enable rolling sessions in SessionMiddleware Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Set rolling=True to extend the session lifetime on every response, effectively expiring the session only after a period of inactivity. ```python from starlette.middleware import Middleware from starsessions import SessionMiddleware middleware = [ Middleware(SessionMiddleware, lifetime=300, rolling=True), ] ``` -------------------------------- ### Configure Redis key prefix Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Customize the session key prefix using a string or a callable function. ```python from redis.asyncio import Redis from starsessions.stores.redis import RedisStore client = Redis.from_url('redis://localhost') store = RedisStore(connection=client, prefix='my_sessions.') ``` ```python from redis.asyncio import Redis from starsessions.stores.redis import RedisStore def make_prefix(key: str) -> str: return 'my_sessions_' + key client = Redis.from_url('redis://localhost') store = RedisStore(connection=client, prefix=make_prefix) ``` -------------------------------- ### Run a Single Test with Uvicorn Source: https://github.com/alex-oleshkevich/starsessions/blob/master/AGENTS.md Execute a specific test case using the `uv` command with `pytest`. ```bash uv run pytest tests/test_middleware.py::test_loads_empty_session ``` -------------------------------- ### Type Check Code with Mypy Source: https://github.com/alex-oleshkevich/starsessions/blob/master/AGENTS.md Perform static type checking on the project using `uv` and `mypy`. ```bash uv run mypy starsessions tests ``` -------------------------------- ### Manually Load Session in View Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Demonstrates the necessity of calling `load_session` before accessing or modifying session data within a request handler. ```python async def index_view(request): await load_session(request) request.session['key'] = 'value' ``` -------------------------------- ### Configure AES-GCM Encryption Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Uses AES-GCM for session encryption, requiring a 256-bit key. ```python import os from starlette.middleware import Middleware from starsessions import CookieStore, SessionMiddleware from starsessions.encryptors import AESGCMEncryptor key = os.urandom(32) # 256-bit key — store securely, never hard-code middleware = [ Middleware( SessionMiddleware, store=CookieStore(secret_key="..."), encryptor=AESGCMEncryptor(key), ) ] ``` -------------------------------- ### Implement a Custom Encryptor Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Defines a custom encryption strategy by implementing the Encryptor abstract class. ```python from starsessions.encryptors import Encryptor class MyEncryptor(Encryptor): async def encrypt(self, data: bytes) -> bytes: ... async def decrypt(self, data: bytes) -> bytes: ... ``` -------------------------------- ### Create session-only cookies Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Set lifetime=0 to create a cookie that is removed by the browser upon closure. ```python from starlette.middleware import Middleware from starsessions import SessionMiddleware middleware = [ Middleware(SessionMiddleware, lifetime=0), ] ``` -------------------------------- ### Configure JsonSerializer with Custom Encoders Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Use custom JSON encoders and decoders to handle non-standard data types like datetime objects within session data. ```python import json from datetime import datetime from starlette.middleware import Middleware from starsessions import JsonSerializer, SessionMiddleware, CookieStore # Custom encoder for datetime objects class DateTimeEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return {"__datetime__": obj.isoformat()} return super().default(obj) class DateTimeDecoder(json.JSONDecoder): def __init__(self, *args, **kwargs): super().__init__(object_hook=self.object_hook, *args, **kwargs) def object_hook(self, obj): if "__datetime__" in obj: return datetime.fromisoformat(obj["__datetime__"]) return obj serializer = JsonSerializer( json_encoder=DateTimeEncoder, json_decoder=DateTimeDecoder, ) middleware = [ Middleware( SessionMiddleware, store=CookieStore(secret_key="secret"), serializer=serializer, ), ] ``` -------------------------------- ### Restrict session cookie path Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Use cookie_path to bind the session cookie to a specific URL prefix. ```python from starlette.middleware import Middleware from starsessions import SessionMiddleware middleware = [ Middleware(SessionMiddleware, cookie_path='/admin'), ] ``` -------------------------------- ### Manage Session Data in Routes Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Access and modify session data within FastAPI route handlers. ```python @app.get("/") async def homepage(request: Request) -> JSONResponse: """Display current session data.""" return JSONResponse(dict(request.session)) @app.get("/set") async def set_data(request: Request) -> RedirectResponse: """Set session data.""" request.session["timestamp"] = datetime.datetime.now().isoformat() request.session["user_agent"] = request.headers.get("user-agent", "unknown") return RedirectResponse("/") @app.post("/login") async def login(request: Request) -> JSONResponse: """Login endpoint with session ID regeneration.""" form = await request.form() request.session["user"] = form.get("username") request.session["authenticated"] = True # Regenerate ID after authentication new_id = regenerate_session_id(request) return JSONResponse({"status": "logged_in", "session_id": new_id}) @app.post("/logout") async def logout(request: Request) -> RedirectResponse: """Logout - clears session data and cookie.""" request.session.clear() return RedirectResponse("/") ``` -------------------------------- ### Clear Session Manually Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Clears the current session data. ```python request.session.clear() ``` -------------------------------- ### Regenerate Session ID in Python Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Use `regenerate_session_id` after sensitive operations like user sign-in to prevent session fixation attacks. Ensure the `starsessions` library is imported. ```python from starsessions import regenerate_session_id from starlette.responses import Response async def login(request): regenerate_session_id(request) return Response('successfully signed in') ``` -------------------------------- ### Restrict session cookie domain Source: https://github.com/alex-oleshkevich/starsessions/blob/master/README.md Use cookie_domain to limit the cookie to specific hosts, noting that this also makes the cookie available to subdomains. ```python from starlette.middleware import Middleware from starsessions import SessionMiddleware middleware = [ Middleware(SessionMiddleware, cookie_domain='example.com'), ] ``` -------------------------------- ### Regenerate session ID in Starlette Source: https://context7.com/alex-oleshkevich/starsessions/llms.txt Use to prevent session fixation attacks after authentication state changes. Requires loading the session before calling the regeneration function. ```python from starlette.requests import Request from starlette.responses import RedirectResponse from starsessions import load_session, regenerate_session_id async def login(request: Request) -> RedirectResponse: await load_session(request) form_data = await request.form() username = form_data.get("username") password = form_data.get("password") # Validate credentials (simplified example) if username == "admin" and password == "secret": # Store user info in session request.session["user_id"] = 1 request.session["username"] = username # IMPORTANT: Regenerate session ID after login to prevent fixation attacks new_session_id = regenerate_session_id(request) print(f"New session ID: {new_session_id}") return RedirectResponse("/dashboard", status_code=302) return RedirectResponse("/login?error=invalid", status_code=302) async def logout(request: Request) -> RedirectResponse: await load_session(request) # Clear session data - middleware will remove cookie and backend data request.session.clear() return RedirectResponse("/", status_code=302) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.