{"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":"python","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,"search_vec":"'1.13.0':52 'activ':44 'applic':21 'back':31 'back-end':30 'beaker':1,4 'cach':3,11,53 'current':48 'decor':23 'end':32 'file':34 'function':15 'includ':16 'librari':8,42 'like':33 'maintain':45 'manag':14 'memcach':36 'memori':35 'middlewar':18,56 'mongodb':38 'provid':9 'python':7 'redi':37 'robust':10 'script':26 'session':2,13,54 'sqlalchemi':40 'stabl':49 'standalon':25 'support':28 'various':29 'version':50 'web':20,57 'wsgi':17,55","created_at":"2026-04-16T18:47:19.707053+00:00","updated_at":"2026-04-16T18:47:19.707053+00:00","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')"}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"1.14.1","cli_name":"","cli_version":null,"type":"library","homepage":"https://beaker.readthedocs.io/","github":null,"docs":null,"changelog":null,"pypi":"https://pypi.org/project/beaker/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["database","web-framework","http-networking"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-06-28","next_check":"2026-07-28","install_tag":null}}