{"id":8879,"library":"beaker","title":"Beaker (Session & Caching)","description":"Beaker is a Python library providing robust caching and session management functionality, including WSGI middleware for web applications and decorators for standalone scripts. It supports various back-ends like file, memory, Memcached, Redis, MongoDB, and SQLAlchemy. The library is actively maintained, with the current stable version being 1.13.0.","status":"active","version":"1.13.0","language":"en","source_language":"en","source_url":"https://github.com/bbangert/beaker","tags":["caching","sessions","wsgi","middleware","web"],"install":[{"cmd":"pip install beaker","lang":"bash","label":"Install stable version"}],"dependencies":[],"imports":[{"note":"SessionMiddleware resides within the middleware submodule.","wrong":"from beaker import SessionMiddleware","symbol":"SessionMiddleware","correct":"from beaker.middleware import SessionMiddleware"},{"note":"CacheManager is part of the cache submodule.","wrong":"from beaker import CacheManager","symbol":"CacheManager","correct":"from beaker.cache import CacheManager"}],"quickstart":{"code":"import os\nfrom wsgiref.simple_server import make_server\nfrom beaker.middleware import SessionMiddleware\n\n\ndef simple_app(environ, start_response):\n    session = environ['beaker.session']\n    if 'counter' in session:\n        session['counter'] += 1\n    else:\n        session['counter'] = 1\n    \n    response_body = [\n        f'The current counter is: {session[\"counter\"]}\\n'.encode('utf-8'),\n        b'Visit this page again to increment.'\n    ]\n    status = '200 OK'\n    headers = [('Content-type', 'text/plain')]\n    start_response(status, headers)\n    return response_body\n\n\n# Configure session options\nsession_opts = {\n    'session.type': 'file',\n    'session.cookie_expires': True,\n    'session.data_dir': './data/sessions/data',\n    'session.lock_dir': './data/sessions/lock'\n}\n\n# Wrap the WSGI application with SessionMiddleware\napplication = SessionMiddleware(simple_app, session_opts)\n\n# Run a simple WSGI server\nif __name__ == '__main__':\n    httpd = make_server('', 8000, application)\n    print(\"Serving on port 8000...\")\n    print(\"You can view the application at http://localhost:8000\")\n    try:\n        httpd.serve_forever()\n    except KeyboardInterrupt:\n        print(\"Shutting down server.\")\n\n# To clean up: remove the ./data/sessions directory created by the example.","lang":"python","description":"This quickstart demonstrates how to integrate Beaker's `SessionMiddleware` with a basic WSGI application. It configures a file-based session to track a counter across requests. Make sure the `data_dir` and `lock_dir` paths exist or are writable by the application."},"warnings":[{"fix":"Create the specified directories and set appropriate permissions (e.g., `os.makedirs('./data/sessions/data', exist_ok=True)`) or choose different backend types suitable for your deployment.","message":"When using file-based or DBM backends, ensure the `session.data_dir` and `session.lock_dir` (or `cache.data_dir`, `cache.lock_dir`) directories are writable by the application. In production, these should be persistent and properly managed.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Configure `session.data_serializer = 'json'` in your session options. Ensure all data stored in the session is JSON-serializable. Otherwise, only store basic, trusted, and serializable Python types.","message":"Storing arbitrary Python objects in sessions using the default `pickle` serializer can lead to security vulnerabilities and issues with unpickleable objects. It is recommended to switch to `json` serialization if your session data permits.","severity":"deprecated","affected_versions":"All versions"},{"fix":"For production environments, use persistent backends like `file`, `dbm`, `memcached`, `redis`, or `mongodb` for session storage to ensure data survives process restarts.","message":"The `memory` backend for sessions is process-local. Session data will be lost if the application process restarts. This backend is generally suitable for development only.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Upgrade Beaker to version 1.9.1 or higher. The fix was included in release 1.9.1 (2018-04-09).","message":"In `beaker` versions prior to 1.9.1, `async` was used as a variable name in some internal code, which became a keyword in Python 3.7. This can lead to `SyntaxError` when running on Python 3.7 or newer.","severity":"breaking","affected_versions":"<1.9.1"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure your WSGI application is wrapped by `SessionMiddleware` with proper configuration, e.g., `application = SessionMiddleware(your_app, session_opts)`.","cause":"The `SessionMiddleware` was not correctly applied to the WSGI application, or the application code is attempting to access `environ['beaker.session']` before it has been made available by the middleware.","error":"<type 'exceptions.KeyError'> at / 'beaker.session'"},{"fix":"Refactor your code to store only primitive types or objects that are known to be pickleable. Alternatively, configure Beaker to use a different serializer: `session_opts = {..., 'session.data_serializer': 'json'}` (if your data is JSON-compatible).","cause":"You are attempting to store an object in the session that cannot be serialized by Python's `pickle` module, which is Beaker's default serializer.","error":"TypeError: can't pickle <_io.TextIOWrapper object at ...>"},{"fix":"Upgrade the Beaker library to version 1.9.1 or later (`pip install --upgrade beaker`) to resolve the keyword conflict.","cause":"You are running an older version of Beaker (<1.9.1) on Python 3.7 or newer, where 'async' became a reserved keyword, causing a syntax error in Beaker's internal code.","error":"SyntaxError: invalid syntax (on a line containing 'async')"}]}