{"id":6967,"library":"aiohttp-session","title":"aiohttp-session","description":"aiohttp-session is a Python library that provides robust session management for aiohttp.web applications. It enables developers to store user-specific data across multiple requests using various storage backends, including secure encrypted cookies, Redis, and Memcached. The library maintains an active development pace, with the current version being 2.12.1, and focuses on stability, security, and compatibility with the latest Python and aiohttp versions.","status":"active","version":"2.12.1","language":"en","source_language":"en","source_url":"https://github.com/aio-libs/aiohttp_session/","tags":["aiohttp","session management","web development","asyncio","cookie storage","redis"],"install":[{"cmd":"pip install aiohttp-session","lang":"bash","label":"Core library"},{"cmd":"pip install aiohttp-session[secure]","lang":"bash","label":"For EncryptedCookieStorage"},{"cmd":"pip install aiohttp-session[aioredis]","lang":"bash","label":"For RedisStorage (installs 'redis' since v2.12.0)"}],"dependencies":[{"reason":"Core web framework dependency.","package":"aiohttp"},{"reason":"Required for EncryptedCookieStorage. Installed via 'aiohttp-session[secure]' extra.","package":"cryptography","optional":true},{"reason":"Required for RedisStorage. Installed via 'aiohttp-session[aioredis]' extra (since v2.12.0).","package":"redis","optional":true},{"reason":"Required for MemcachedStorage.","package":"aiomcache","optional":true}],"imports":[{"symbol":"get_session","correct":"from aiohttp_session import get_session"},{"symbol":"setup","correct":"from aiohttp_session import setup"},{"symbol":"EncryptedCookieStorage","correct":"from aiohttp_session.cookie_storage import EncryptedCookieStorage"},{"symbol":"RedisStorage","correct":"from aiohttp_session.redis_storage import RedisStorage"},{"symbol":"Fernet","correct":"from cryptography.fernet import Fernet"}],"quickstart":{"code":"import asyncio\nimport os\nfrom cryptography import fernet\nfrom aiohttp import web\nfrom aiohttp_session import get_session, setup\nfrom aiohttp_session.cookie_storage import EncryptedCookieStorage\n\nasync def handler(request):\n    session = await get_session(request)\n    last_visit = session.get('last_visit', 'Never')\n    session['last_visit'] = str(request.app['current_time'])\n    text = f\"Last visited: {last_visit}\\nHello, current time is {session['last_visit']}\"\n    return web.Response(text=text)\n\nasync def make_app():\n    app = web.Application()\n    \n    # Generate a Fernet key. In production, this should be stored securely\n    # and loaded from environment variables or a secret management system.\n    # Using a dummy key for demonstration purposes.\n    fernet_key_str = os.environ.get('AIOHTTP_SESSION_KEY', None)\n    if fernet_key_str is None:\n        # WARNING: DO NOT generate a new key on every app startup in production!\n        # A new key invalidates all existing sessions. Load from a persistent source.\n        fernet_key = fernet.Fernet.generate_key()\n        print(f\"Generated new Fernet key (for demo only): {fernet_key.decode()}\\nSet AIOHTTP_SESSION_KEY env var in production.\")\n    else:\n        fernet_key = fernet_key_str.encode()\n\n    f = fernet.Fernet(fernet_key)\n    setup(app, EncryptedCookieStorage(f))\n    app['current_time'] = 'Not set yet'\n    app.router.add_get('/', handler)\n    return app\n\nasync def main():\n    app = await make_app()\n    runner = web.AppRunner(app)\n    await runner.setup()\n    site = web.TCPSite(runner, 'localhost', 8080)\n    await site.start()\n    print(\"Server started at http://localhost:8080\")\n    try:\n        while True:\n            app['current_time'] = asyncio.get_event_loop().time()\n            await asyncio.sleep(1)\n    except asyncio.CancelledError:\n        pass\n    finally:\n        await runner.cleanup()\n\nif __name__ == '__main__':\n    try:\n        asyncio.run(main())\n    except KeyboardInterrupt:\n        print(\"Server stopped.\")","lang":"python","description":"This quickstart demonstrates setting up a basic aiohttp.web application with session management using EncryptedCookieStorage. It initializes a Fernet key (generating one if not provided via environment variable, highlighting the need for persistence in production), registers the session middleware with `setup()`, and uses `get_session()` within a handler to store and retrieve user visit times. Run the server, then access `http://localhost:8080` in your browser to see session data persist."},"warnings":[{"fix":"Upgrade your Python environment to 3.8 or higher.","message":"Support for Python 3.7 was dropped in `aiohttp-session` v2.12.1. Applications running on Python 3.7 will need to upgrade their Python version.","severity":"breaking","affected_versions":">=2.12.1"},{"fix":"If using RedisStorage, ensure `pip install redis` or `pip install aiohttp-session[aioredis]` is used. The `[aioredis]` extra will now install `redis`.","message":"Starting with `aiohttp-session` v2.12.0, `RedisStorage` migrated its core dependency from `aioredis` to `redis`. If you were manually installing `aioredis` for Redis sessions without using the `[aioredis]` extra, you must now install `redis` instead.","severity":"breaking","affected_versions":">=2.12.0"},{"fix":"For production environments, always use `EncryptedCookieStorage` or a server-side storage like `RedisStorage` or `MemcachedStorage`.","message":"Using `SimpleCookieStorage` directly is insecure as it stores session data in plain JSON. It is strictly recommended for testing or development purposes only.","severity":"gotcha","affected_versions":"All"},{"fix":"Replace `await get_session(request)` with `await new_session(request)` in code paths where a user's authentication status changes (e.g., after login).","message":"To prevent session fixation attacks, always call `new_session()` in login views to generate a fresh session identity for authenticated users.","severity":"gotcha","affected_versions":"All"},{"fix":"Generate a `Fernet.generate_key()` once and persist it securely (e.g., in an environment variable or a secret management service) across application restarts. Pass this consistent key to `EncryptedCookieStorage`.","message":"The `EncryptedCookieStorage` requires a strong 32-byte secret key (or a `Fernet` object) for encryption. Generating a new key on every application restart will invalidate all existing sessions, logging out users.","severity":"gotcha","affected_versions":"All"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"If on `aiohttp-session < 2.12.0`, ensure `pip install aioredis`. If on `aiohttp-session >= 2.12.0`, ensure `pip install redis` or `pip install aiohttp-session[aioredis]`.","cause":"Prior to v2.12.0, the `aioredis` extra explicitly required the `aioredis` package. Post v2.12.0, it shifted to `redis`.","error":"RuntimeError: Cannot install aiohttp_session[aioredis] without aioredis library"},{"fix":"Verify that the Fernet encryption key used by `EncryptedCookieStorage` is consistent across all application instances and restarts. Ensure that `Fernet.generate_key()` is not called repeatedly in production. Users with invalid cookies will simply receive a new session.","cause":"This error often indicates that the `EncryptedCookieStorage` received a cookie it couldn't decrypt. Common causes include a corrupted session cookie, or the application's encryption key changing between server restarts.","error":"cryptography.fernet.InvalidToken: Message too short"},{"fix":"Use `setup(app, storage_instance)` to configure the session middleware, or pass `session_middleware(storage_instance)` directly to the `middlewares` list when creating `web.Application`.","cause":"The `session_middleware` function is typically called as `session_middleware(storage_instance)` and then passed to `app.middlewares`. If `setup(app, storage_instance)` is used, you generally don't interact with `session_middleware` directly.","error":"TypeError: session_middleware() got an unexpected keyword argument 'storage'"},{"fix":"Ensure `aiohttp_session.setup(app, storage)` is called on the `web.Application` instance that handles your routes, or that `session_middleware(storage)` is properly included in the `middlewares` list of `web.Application`.","cause":"This usually means the session middleware is not correctly registered or the `aiohttp.web.Application` instance receiving requests is not the one configured with the session middleware.","error":"KeyError: 'AIOHTTP_SESSION' (or other cookie name) or session data not persisting between requests."}]}