""" Demonstrating sessions for guest users (no Google login required). Two things are shown here: a. Setting/receiving a cookie holding a session key b. Using the session key to store/load per-user session data. This is almost completely generic WSGI code. The only AppEngine piece is the use of memcache to store the session data. From boodebr.appspot.com. May be freely used and modified for any purpose. """ from Cookie import SimpleCookie import datetime as DT import os, sha, pickle from random import randint import google.appengine.api.memcache as mcache def sesskey(): "Create a session key" # session key is 40-byte hexstring = 160 bits, so create # it using 20 random bytes = 160 bits return sha.new(os.urandom(20)).hexdigest() def makeval(): "Create a random value to use as the session data." return (randint(0, 40), randint(0, 40), randint(0, 40)) def session_demo(environ, start_response): path = environ['PATH_INFO'] if path == '/sessdemo/source': status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) return [open(__file__).read()] status = '200 OK' response_headers = [('Content-type','text/html')] # parse any cookies that client sent me jar = SimpleCookie() jar.load(environ.get('HTTP_COOKIE', '')) h = '' #h += 'HTTP_COOKIE: %s\n' % environ.get('HTTP_COOKIE', '') ind = ' '*3 if not jar.has_key('short-cookie'): # create new cookie "short-cookie" with value=session key skey = sesskey() jar['short-cookie'] = skey # set to expire in 60 seconds exp = DT.datetime.utcnow() + DT.timedelta(seconds=60) jar['short-cookie']['expires'] = exp.strftime("%a, %d %b %Y %H:%M:%S %z") # send new cookie to client via Set-Cookie response_headers += [('Set-Cookie', jar['short-cookie'].OutputString())] # make some session data and store in memcache val = makeval() # have it expire the same time as the cookie mcache.set('short-cookie-data-%s' % skey, pickle.dumps(val), time=60) # tell user what is happening h += 'Making new short-cookie
' h += "(This cookie will expire in 60 seconds!)
" h += ind+ 'key=%s
' % skey h += ind + 'storing session data: %s

' % str(val) h += '*** Reload now to see that the session data was saved OK. ***

' else: # got cookie, load session data and show user h += "Got short-cookie:
" skey = jar['short-cookie'].value h += ind + 'key=%s
' % skey data = mcache.get('short-cookie-data-%s' % skey) if data is None: h += ind + 'ERROR LOADING SESSION DATA

' else: val = pickle.loads(data) h += ind + 'loaded session data=%s

' % str(val) h += '*** Wait a minute, then reload to see that the key expires and new one is generated. ***

' # display the headers I'm sending h += 'sending headers:


' for k,v in response_headers: h += ind + '%s: %s
' % (k,v) h += '
' h += 'Return to boodebr@appspot' # send response start_response(status, response_headers) return [h] # does not know nor care that it is running under AppEngine! from wsgiref.handlers import CGIHandler CGIHandler().run(session_demo)