Skip to content

Instantly share code, notes, and snippets.

@soundkitchen
Created May 23, 2012 10:08
Show Gist options
  • Save soundkitchen/2774392 to your computer and use it in GitHub Desktop.
Save soundkitchen/2774392 to your computer and use it in GitHub Desktop.
werkzeug な redis 使った SessionStore とかとか
# vim: fileencoding=utf-8 :
from werkzeug.contrib.sessions import SessionMiddleware
from sessions import RedisSessionStore
def create_application():
app = Application()
app = SessionMiddleware(app, RedisSessionStore())
return app
class Application(object):
def __init__(self):
pass
def __call__(self, environ, start_response):
(snip)
# vim: fileencoding=utf-8 :
import msgpack
from redis import Redis
from werkzeug.contrib.sessions import SessionStore, Session
class RedisSessionStore(SessionStore):
"""session store using redis."""
def __init__(self, host='localhost', port=6379, db=0, expire=0, session_class=None):
super(RedisSessionStore, self).__init__(session_class=session_class)
self._conn = Redis(host=host, port=port, db=db)
self._expire = int(expire)
def save(self, session):
packed = msgpack.dumps(dict(session))
self._conn.set(session.sid, packed)
def delete(self, session):
self._conn.delete(session.sid)
def get(self, sid):
if not self.is_valid_key(sid):
return self.new()
packed = self._conn.get(sid)
try:
data = msgpack.loads(packed, encoding='utf-8')
if self._expire:
self._conn.expire(sid, self._expire)
except TypeError, e:
data = {}
return self.session_class(data, sid, False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment