#!/usr/bin/python """A session demonstration app.""" import calendar from datetime import datetime import sys import cherrypy from cherrypy.lib import sessions from cherrypy._cpcompat import copyitems page = """

Session Demo

Reload this page. The session ID should not change from one reload to the next

Index | Expire | Regenerate

Session ID:%(sessionid)s

%(changemsg)s

Request Cookie%(reqcookie)s
Response Cookie%(respcookie)s

Session Data%(sessiondata)s
Server Time%(servertime)s (Unix time: %(serverunixtime)s)
Browser Time 
Cherrypy Version:%(cpversion)s
Python Version:%(pyversion)s
""" class Root(object): def page(self): changemsg = [] if cherrypy.session.id != cherrypy.session.originalid: if cherrypy.session.originalid is None: changemsg.append('Created new session because no session id was given.') if cherrypy.session.missing: changemsg.append('Created new session due to missing (expired or malicious) session.') if cherrypy.session.regenerated: changemsg.append('Application generated a new session.') try: expires = cherrypy.response.cookie['session_id']['expires'] except KeyError: expires = '' return page % { 'sessionid': cherrypy.session.id, 'changemsg': '
'.join(changemsg), 'respcookie': cherrypy.response.cookie.output(), 'reqcookie': cherrypy.request.cookie.output(), 'sessiondata': copyitems(cherrypy.session), 'servertime': datetime.utcnow().strftime("%Y/%m/%d %H:%M") + " UTC", 'serverunixtime': calendar.timegm(datetime.utcnow().timetuple()), 'cpversion': cherrypy.__version__, 'pyversion': sys.version, 'expires': expires, } def index(self): # Must modify data or the session will not be saved. cherrypy.session['color'] = 'green' return self.page() index.exposed = True def expire(self): sessions.expire() return self.page() expire.exposed = True def regen(self): cherrypy.session.regenerate() # Must modify data or the session will not be saved. cherrypy.session['color'] = 'yellow' return self.page() regen.exposed = True if __name__ == '__main__': cherrypy.config.update({ #'environment': 'production', 'log.screen': True, 'tools.sessions.on': True, }) cherrypy.quickstart(Root())