Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

Using Beaker session with Flask

Posted by Simon Lyngshede on 2011-07-25 @ 20:47 and filed in Sessions

The following is a simple application that shows how to bootstrap beakers session middleware and access the session variables. The example uses memcached as the backend.

from flask import Flask, request
from beaker.middleware import SessionMiddleware

session_opts = {
    'session.type': 'ext:memcached',
    'session.url': '',
    'session.data_dir': './cache',

app = Flask(__name__)       

def index():
    session = request.environ['beaker.session']
    if not session.has_key('value'):
        session['value'] = 'Save in session' 
        return "Session value set."
        return session['value']
if __name__ == '__main__':
    app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts)

You might want to use beaker in the situation where you have multiple Flask applications, e.g. load balanced applications, that need to have access to a shared session storage, which beaker can provide.

This snippet by Simon Lyngshede can be used freely for anything you like. Consider it public domain.