Flask Snippets

Beaker session in Flask

By Piotr Sensu filed in Sessions

This is an extension to snippet Using Beaker session with Flask that gives more seamless beaker session integration by using SessionInterface.

from flask import Flask, session
from flask.sessions import SessionInterface
from beaker.middleware import SessionMiddleware

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

class BeakerSessionInterface(SessionInterface):
    def open_session(self, app, request):
        session = request.environ['beaker.session']
        return session

    def save_session(self, app, session, response):

app = Flask(__name__)       

def index():
    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)
    app.session_interface = BeakerSessionInterface()

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