1.11.3 Creating a basic session environment

The web.session module is designed so that the data can be stored in ways using different drivers. Currently only a database storage driver and file driver exist allowing auth information to be stored in any relational database supported by the web.database module or in a sirectory structure.

In this example we are using a database to store the auth and session information so we setup a database cursor named cursor as described in the documentation for the web.database module.

import web.database
connection = web.database.connect(adapter='snakesql', database='test', autoCreate=1)
cursor = connection.cursor()

Next we need to create the necessary tables which will store the session information. To do this we use the SessionManager object.

manager = web.session.manager(driver='database', cursor=cursor)

If we haven't already created the session tables we can do so like this:

if not manager.completeSessionEnvironment():
    manager.removeSessionEnvironment(ignoreErrors=True)
    manager.createSessionEnvironment()

Alternatively the session manager can also take the autoCreate=1 parameter to automatically create the necessary tables in exactly the way described above automatically.

If any of the tables are missing, this code removes all existing tables thereby destroying all the data they contain (ignoring errors produced because of missing tables) and re-creates all the tables.

connection.commit()

The connection.commit() saves the changes to the database.

web.session.manager() also takes a range of parameters such as expire to set the length of time in seconds the session is valid for or cookie to set the cookie options. The full list of options is listed in the API reference section but the default values are usually adequate.