Use Beaker session with Flask

Flask is a great web (micro)framework for Python. But it’s default session implementation is a little too weak to some applications, especially when you need to save more than a few bytes in the session. Beaker is a powerful web session library, but Flask is not friendly to switch session manager.

After some tweaking, I found the clean way to do this. Instead of using beaker’s SessionMiddleware, which makes the session environment request.environ[‘beaker.session’], instead of the nature “session”, I used MixIn pattern. Now it’s just a bunch of code, maybe later I can make it a real extension.

Here comes the code.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from beaker.session import Session, SessionObject
from flask import Flask, request, session

class BeakerMixin(object):
    beaker_opts = {'type':'file', 'data_dir':'sessions', 'timeout':3600,
        'auto':True, 'cookie_expires':True, 'invalidate_corrupt':True}

    def open_session(self, request):
        return SessionObject(request.environ, key=self.session_cookie_name,
            **self.beaker_opts)

    def save_session(self, session, response):
        if session.accessed():
            session.persist()
            data = session.__dict__['_headers']
            if data['set_cookie'] and data['cookie_out']:
                response.headers['Set-Cookie'] = data['cookie_out']

class BeakerSessionFlask(BeakerMixin, Flask): pass

app = BeakerSessionFlask('test_beaker')

@app.route('/')
def index():
    try: session['cpt'] += 1
    except KeyError: session['cpt'] = 1
    return 'sid: %s, cpt: %d' % (session.id, session['cpt'])

if __name__ == '__main__':
    # app.secret_key is not required
    app.run(host='0.0.0.0', port=8080, debug=True)

Compile modern Linux kernel on RHEL4

Kernel version: 2.6.35.11, used for server.

Although Documentation/Changes wants gcc 3.2, it can’t compile on gcc 3.4 comes with RHEL/CentOS 4. Most programs seem to compile with a little warning, but several drivers need later compiler features.

Fortunately, RHEL/CentOS 4 provides gcc4 (4.1.2) in later updates. The kernel compiles perfectly with it. But I found it’s a little tricky to tell the building system (KBuild?) to use gcc4 instead of gcc: there’re no stuff like configure, and Makefile doesn’t accept CC environment variables. And I can’t find any documents with Google… Finally I found modifying top level Makefile works: just set HOSTCC to gcc4, and CC to $(CROSS_COMPILE)/gcc4. I’m not sure the difference between HOSTCC and CC. It seems like HOSTCC is for programs for “make menuconfig”, while CC is for the actual kernel code.

I can’t use “make -j” with the default make version comes with RHEL4 (3.80). After upgrading to 3.81, it works just fine.