Tornado really doesn’t have a great native session handler, so I created a custom solution combining Tornado with Redis for session management.
Session Storage Implementation
The RedisSessionStore class manages backend operations:
- Initializes with configurable key prefixes and expiration times (default: 60 days)
- Generates session IDs using UUID
- Stores/retrieves pickled session data in Redis hash structures
- Automatically expires sessions based on configuration
Session Wrapper Class
The Session class provides a dictionary-like interface:
- Lazy-loads session data from Redis
- Tracks modification state via a “dirty” flag
- Implements standard Python container methods (
__getitem__,__setitem__, etc.) - Records access timestamps with IP addresses
- Auto-saves changes upon deletion
Tornado Integration
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
return self.session['user'] if self.session and 'user' in self.session else None
@property
def session(self):
sessionid = self.get_secure_cookie('AUTH_COOKIE', None)
if sessionid:
return Session(self.application.session_store, sessionid)
else:
sess = Session(self.application.session_store, None)
self.set_secure_cookie('AUTH_COOKIE', sess.sessionid)
return sess
The implementation works with local Redis instances but supports remote connections through customized parameters.