caines.ca/blog Shell-Shocked Ramblings from the Trenches of Software Development

27Oct/092

Sessions in Tornado

In case anyone's interested, here's my sessions.py that I use for doing a pickle-based session (stored as a file in a directory of your choosing) in Tornado.  Feel free to use it however you please.   If I write something more scalable one day, I'll post it too.

Here's the basic usage:

In your application script,

settings["session_secret"] = 'some secret password!!'
settings["session_dir"] = 'sessions'  # the directory to store sessions in
application.session_manager = session.TornadoSessionManager(settings["session_secret"], settings["session_dir"])

In your RequestHandler (probably in __init__),

self.session = session.TornadoSession(self.application.session_manager, self)

After that, you can use it like this (in get(), post(), etc):

self.session['blah'] = 1234
self.save()
blah = self.session['blah']
etc.

The basic session mechanism is this:

  • take a dict, pickle it, store it in the session_dir.
  • assign an id to it. run that id through a HMAC (NOT just a hash function) to prevent tampering.
  • put the id and HMAC output in a cookie.
  • when you get a request, load the id, verify the HMAC. if it matches, load the data from wherever you put it and depickle it.

Bug reports welcome.

Comments (2) Trackbacks (0)
  1. Thanks
    can you write a demo

  2. Great work!


Leave a comment


No trackbacks yet.