Package cherrypy :: Package test :: Module sessiondemo
[hide private]
[frames] | no frames]

Source Code for Module cherrypy.test.sessiondemo

  1  #!/usr/bin/python 
  2  """A session demonstration app.""" 
  3   
  4  import calendar 
  5  from datetime import datetime 
  6  import sys 
  7  import cherrypy 
  8  from cherrypy.lib import sessions 
  9  from cherrypy._cpcompat import copyitems 
 10   
 11   
 12  page = """ 
 13  <html> 
 14  <head> 
 15  <style type='text/css'> 
 16  table { border-collapse: collapse; border: 1px solid #663333; } 
 17  th { text-align: right; background-color: #663333; color: white; padding: 0.5em; } 
 18  td { white-space: pre-wrap; font-family: monospace; padding: 0.5em; 
 19       border: 1px solid #663333; } 
 20  .warn { font-family: serif; color: #990000; } 
 21  </style> 
 22  <script type="text/javascript"> 
 23  <!-- 
 24  function twodigit(d) { return d < 10 ? "0" + d : d; } 
 25  function formattime(t) { 
 26      var month = t.getUTCMonth() + 1; 
 27      var day = t.getUTCDate(); 
 28      var year = t.getUTCFullYear(); 
 29      var hours = t.getUTCHours(); 
 30      var minutes = t.getUTCMinutes(); 
 31      return (year + "/" + twodigit(month) + "/" + twodigit(day) + " " + 
 32              hours + ":" + twodigit(minutes) + " UTC"); 
 33  } 
 34   
 35  function interval(s) { 
 36      // Return the given interval (in seconds) as an English phrase 
 37      var seconds = s %% 60; 
 38      s = Math.floor(s / 60); 
 39      var minutes = s %% 60; 
 40      s = Math.floor(s / 60); 
 41      var hours = s %% 24; 
 42      var v = twodigit(hours) + ":" + twodigit(minutes) + ":" + twodigit(seconds); 
 43      var days = Math.floor(s / 24); 
 44      if (days != 0) v = days + ' days, ' + v; 
 45      return v; 
 46  } 
 47   
 48  var fudge_seconds = 5; 
 49   
 50  function init() { 
 51      // Set the content of the 'btime' cell. 
 52      var currentTime = new Date(); 
 53      var bunixtime = Math.floor(currentTime.getTime() / 1000); 
 54   
 55      var v = formattime(currentTime); 
 56      v += " (Unix time: " + bunixtime + ")"; 
 57   
 58      var diff = Math.abs(%(serverunixtime)s - bunixtime); 
 59      if (diff > fudge_seconds) v += "<p class='warn'>Browser and Server times disagree.</p>"; 
 60   
 61      document.getElementById('btime').innerHTML = v; 
 62   
 63      // Warn if response cookie expires is not close to one hour in the future. 
 64      // Yes, we want this to happen when wit hit the 'Expire' link, too. 
 65      var expires = Date.parse("%(expires)s") / 1000; 
 66      var onehour = (60 * 60); 
 67      if (Math.abs(expires - (bunixtime + onehour)) > fudge_seconds) { 
 68          diff = Math.floor(expires - bunixtime); 
 69          if (expires > (bunixtime + onehour)) { 
 70              var msg = "Response cookie 'expires' date is " + interval(diff) + " in the future."; 
 71          } else { 
 72              var msg = "Response cookie 'expires' date is " + interval(0 - diff) + " in the past."; 
 73          } 
 74          document.getElementById('respcookiewarn').innerHTML = msg; 
 75      } 
 76  } 
 77  //--> 
 78  </script> 
 79  </head> 
 80   
 81  <body onload='init()'> 
 82  <h2>Session Demo</h2> 
 83  <p>Reload this page. The session ID should not change from one reload to the next</p> 
 84  <p><a href='../'>Index</a> | <a href='expire'>Expire</a> | <a href='regen'>Regenerate</a></p> 
 85  <table> 
 86      <tr><th>Session ID:</th><td>%(sessionid)s<p class='warn'>%(changemsg)s</p></td></tr> 
 87      <tr><th>Request Cookie</th><td>%(reqcookie)s</td></tr> 
 88      <tr><th>Response Cookie</th><td>%(respcookie)s<p id='respcookiewarn' class='warn'></p></td></tr> 
 89      <tr><th>Session Data</th><td>%(sessiondata)s</td></tr> 
 90      <tr><th>Server Time</th><td id='stime'>%(servertime)s (Unix time: %(serverunixtime)s)</td></tr> 
 91      <tr><th>Browser Time</th><td id='btime'>&nbsp;</td></tr> 
 92      <tr><th>Cherrypy Version:</th><td>%(cpversion)s</td></tr> 
 93      <tr><th>Python Version:</th><td>%(pyversion)s</td></tr> 
 94  </table> 
 95  </body></html> 
 96  """ 
 97   
 98   
99 -class Root(object):
100
101 - def page(self):
102 changemsg = [] 103 if cherrypy.session.id != cherrypy.session.originalid: 104 if cherrypy.session.originalid is None: 105 changemsg.append( 106 'Created new session because no session id was given.') 107 if cherrypy.session.missing: 108 changemsg.append( 109 'Created new session due to missing ' 110 '(expired or malicious) session.') 111 if cherrypy.session.regenerated: 112 changemsg.append('Application generated a new session.') 113 114 try: 115 expires = cherrypy.response.cookie['session_id']['expires'] 116 except KeyError: 117 expires = '' 118 119 return page % { 120 'sessionid': cherrypy.session.id, 121 'changemsg': '<br>'.join(changemsg), 122 'respcookie': cherrypy.response.cookie.output(), 123 'reqcookie': cherrypy.request.cookie.output(), 124 'sessiondata': copyitems(cherrypy.session), 125 'servertime': ( 126 datetime.utcnow().strftime("%Y/%m/%d %H:%M") + " UTC" 127 ), 128 'serverunixtime': calendar.timegm(datetime.utcnow().timetuple()), 129 'cpversion': cherrypy.__version__, 130 'pyversion': sys.version, 131 'expires': expires, 132 }
133
134 - def index(self):
135 # Must modify data or the session will not be saved. 136 cherrypy.session['color'] = 'green' 137 return self.page()
138 index.exposed = True 139
140 - def expire(self):
141 sessions.expire() 142 return self.page()
143 expire.exposed = True 144
145 - def regen(self):
146 cherrypy.session.regenerate() 147 # Must modify data or the session will not be saved. 148 cherrypy.session['color'] = 'yellow' 149 return self.page()
150 regen.exposed = True
151 152 if __name__ == '__main__': 153 cherrypy.config.update({ 154 #'environment': 'production', 155 'log.screen': True, 156 'tools.sessions.on': True, 157 }) 158 cherrypy.quickstart(Root()) 159