repoze.session Usage

repoze.session is sessioning system for Python web applications.

Using Session Data Objects and Expiration

repoze.session automatically expires sessions which have been inactive for some timeout.

Here is an example of using the sessioning machinery in one of your applications:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from repoze.session.manager import FileStorageSessionManagerFactory
from repoze.session.manager import ConnectionManager

factory = FileStorageSessionManagerFactory('session.db', 'mysessions')

cm = ConnectionManager()
session_manager = factory(cm)
session_data = session_manager.get('abc')
session_data['first_name'] = 'fred'
session_data.invalidate()
session_data = session_manager.get('abc')
assert(not session_data.has_key('first_name'))  # we invalidated it
session_data['last_name'] = 'McDonough'
cm.commit() # we need to commit the session data into the storage

# session data will automatically expire (become invalid) after 20
# minutes of session inactivity.

The value you send in to the session manager’s get method should be a value you’ve managed to assign to a particular user, perhaps via a cookie. See repoze.browserid for a library that manages browser identifiers. These identifiers can be used as session manager keys.

Using Begin and End Subscribers

repoze.session allows you to register session-end and session-begin subscribers in order to react to the start and end of a session.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from zope.component import getGlobalSiteManager
from repoze.session.interfaces import ISessionBeginEvent
from repoze.session.interfaces import ISessionEndEvent

sm = getGlobalSiteManager()

def test_event(event):
    print event.__class__, event.session

sm.registerHandler(test_event, (ISessionBeginEvent,))
sm.registerHandler(test_event, (ISessionEndEvent,))

# when a session ends or begins, it will be printed

Gotchas

Values inserted into a repoze.session session store should not subclass ZODB Persistent class. If they do, there is a chance that irresolveable cross-database references will put into the session manager’s (separate) database.

When the ConnectionManager ‘s commit method is called, it will commit a transaction for all databases participating in Zope transaction management. Don’t use this method if you already have transaction management enabled in another way.

Table Of Contents

Previous topic

Installing repoze.session

Next topic

repoze.session API

This Page