Beaker (Session & Caching)

1.13.0 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import os
from wsgiref.simple_server import make_server
from beaker.middleware import SessionMiddleware


def simple_app(environ, start_response):
    session = environ['beaker.session']
    if 'counter' in session:
        session['counter'] += 1
    else:
        session['counter'] = 1
    
    response_body = [
        f'The current counter is: {session["counter"]}\n'.encode('utf-8'),
        b'Visit this page again to increment.'
    ]
    status = '200 OK'
    headers = [('Content-type', 'text/plain')]
    start_response(status, headers)
    return response_body


# Configure session options
session_opts = {
    'session.type': 'file',
    'session.cookie_expires': True,
    'session.data_dir': './data/sessions/data',
    'session.lock_dir': './data/sessions/lock'
}

# Wrap the WSGI application with SessionMiddleware
application = SessionMiddleware(simple_app, session_opts)

# Run a simple WSGI server
if __name__ == '__main__':
    httpd = make_server('', 8000, application)
    print("Serving on port 8000...")
    print("You can view the application at http://localhost:8000")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("Shutting down server.")

# To clean up: remove the ./data/sessions directory created by the example.

view raw JSON →