#!/usr/bin/python """A session demonstration app.""" import calendar from datetime import datetime import sys import six import cherrypy from cherrypy.lib import sessions 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
""" # noqa E501 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': list(six.iteritems(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, } @cherrypy.expose def index(self): # Must modify data or the session will not be saved. cherrypy.session['color'] = 'green' return self.page() @cherrypy.expose def expire(self): sessions.expire() return self.page() @cherrypy.expose def regen(self): cherrypy.session.regenerate() # Must modify data or the session will not be saved. cherrypy.session['color'] = 'yellow' return self.page() if __name__ == '__main__': cherrypy.config.update({ # 'environment': 'production', 'log.screen': True, 'tools.sessions.on': True, }) cherrypy.quickstart(Root())