If you are using cookies (which is the recommended way of using the web.session module) you may prefer to use the web.session.start() method to handle the loading or creation of the session automatically and return a store for the application specified. Note: This will print the cookie headers straight away so this method will not work with WSGI applications or other non CGI environments. If you are unsure it is better to use the longer method.
Below is an example which uses the start()
method:
#!/usr/bin/env python # show python where the modules are import sys; sys.path.append('../'); sys.path.append('../../../') import web.error; web.error.enable() import os, time import web.database # Setup a database connection connection = web.database.connect( adapter="snakesql", database="webserver-session-simple", autoCreate = 1, ) cursor = connection.cursor() # Create a session driver and make sure the database tables exist import web.session store = web.session.start( app='test', environmentName='testEnv', environmentType='database', expire=10, setupSessionEnvironment=1, cursor = cursor, ) manager = store.manager def printPage(title, url, link, url2, link2, data): print """ <html> <h1>%s</h1> <p><a href="%s">%s</a></p> <p><a href="%s">%s</a></p> <p>%s</p> </html>"""%(title, url, link, url2, link2, data) # Write a simple application if not manager.created: if web.cgi.has_key('destroy') and web.cgi['destroy'].value == 'True': manager.destroy(ignoreWarning=True, sendCookieHeaders=False) manager.sendCookieHeaders() print web.header('text/html') printPage( 'Session Destroyed', os.environ['SCRIPT_NAME'], 'Start Again', '','','' ) else: print web.header('text/html') manager.setExpire(manager.expireTime+5) data = [] data.append('SessionID: ' +manager.sessionID) data.append('Store Keys: '+str(store.keys())) data.append('Store App: '+store.app) data.append('Variable1: '+str(store['Variable1'])) data.append('ExpireTime: '+str(manager.expireTime)) printPage( 'Welcome back', os.environ['SCRIPT_NAME'], 'Visit Again', os.environ['SCRIPT_NAME']+'?destroy=True', 'Destroy Session', '<p>Every time you visit this page the expiry \ time increases 5 seconds</p>'+'</p><p>'.join(data) ) else: print web.header('text/html') store['Variable1'] = 'Python Rules!' printPage( 'New Session Started', os.environ['SCRIPT_NAME'], 'Visit Again', '', '', "Set variable1 to 'Python Rules!'" ) connection.commit() # Save changes connection.close() # Close the database connection
You can test this example by running the webserver scripts/webserver.py and visiting http://localhost:8080/doc/src/lib/webserver-web-session-simple.py