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.
January 12th, 2011 - 21:15
Thanks
can you write a demo
March 7th, 2011 - 02:35
Great work!
April 25th, 2012 - 00:09
Why not to store just random string in cookie? why we need password, uuid, hmac, sha1 ? why not to store cookies on a server, using that random as a key?