Posts for the month of June 2013

Use Redis as a session backend

Recently I used Redis in one of our projects, while looking for documentation about it I stumbled upon this article about configuring Redis as a LRU cache. I decided to try and write a little session manager for Nagare using Redis as backend.


Nagare Installation

Many Nagare mechanisms can be extended through the use of entry points. The Nagare entry point I used is nagare.sessions:

redis = nagare.sessions.redis:Sessions

nagare.sessions.redis:Sessions is the path to the Session manager implementation class.

Session Manager API

Redis Session manager has to inherit from nagare.sessions.common.Sessions

from nagare.sessions import common
class Sessions(common.Sessions):

The following methods must be implemented:

  • Save an application state to your backend:
def serialize(self, data):
    """Serialize application state."""
def _set(self, session_id, state_id, secure_id, use_same_state, session_data, state_data):
    """Store the serialized state and sessions state into our backend"""
  • Retrieve and restore application state from your backend
def deserialize(self, session_data, state_data):
    """Deserialize application serialized state and session"""
def _get(self, session_id, state_id, use_same_state):
    """Retrieve serialized state from our backend"""
  • Create and delete state
def _create(self, session_id, secure_id):
    """Create a new session in our backend"""
def _delete(self, session_id):
    """Delete a session"

The whole code, with handling of locks and other low level stuff can be viewed here.

Use Redis Session Manager

Now, to use the newly created session manager, you have to create a publisher configuration file. The sessions section is configured as this:

type = redis

Finally I manage to replace seamlessly the standard Nagare session managers by the Redis one I wrote. Hopefully the same technique can be used to try out any other session backend for Nagare.


As pointed out by expo on Nagare mailing list version linked in this post does not work with Nagare latest version. The working version he submitted is available.