The shelve moduleΒΆ

Having a SID is not enough. It is necessary to save the session state in a file or in a database. To save it into a file the shelve module is used. The shelve module opens a file and returns a dictionary like object which is readable and writable as a dictionary:

# The shelve module will persist the session data
# and expose it as a dictionary
session = shelve.open('/tmp/.session/sess_' + sid, writeback=True)

The SID is part of file name making it a unique file. The apache user must have read and write permission on the file’s directory. 660 would be ok.

The values of the dictionary can be any Python object. The keys must be immutable objects:

# Save the current time in the session
session['lastvisit'] = repr(time.time())

# Retrieve last visit time from the session
lastvisit = session.get('lastvisit')

The dictionary like object must be closed as any other file should be:

session.close()