close Warning: Can't synchronize with repository "(default)" (Unsupported version control system "svn": No module named svn). Look in the Trac log for more information.

Session State

The diva.session module implements management of session state, based entirely on client-side storage via HTTP cookies. The cookie used to store the session data contains the serialized session data, and is authenticated using HMAC-SHA1-128 based on a secret key known to the server. This means that the user cannot tamper with the cookie value to modify session state directly, bypassing the server-side application logic that is responsible for managing the session.

Background

Cookie-based session storage is much more efficient than storing the data on the server-side (the way many web applications handle session state), as long as the amount of session state is kept small. Instead of requiring a database fetch every time the session is accessed (which is on every request for most dynamic web applications), there's only the very small cost of decoding and authenticating the session cookie header.

But trying to store large amounts of data in the session will result in a very large session cookie being transmitted back and forth for every HTTP request (also, there's a ~4KB limit to cookie size). Applications that need to track large amounts of state are often better off storing that state in a database explicitly. Such applications can still use the generic session storage to associate the stored state with incoming requests, if necessary.

Usage

When the session filter is enabled (which is the default), a plain Python dict is made available as the application context variable app.ctxt.session. It should usually not be necessary to access that dictionary directly, as the diva.session module provides a couple of module-level functions to read, write and delete session data.

For example, a simple request handler accessing the session might look like this:

from diva import session
from diva.templating import output, render

@output('test.html')
def test(request, response):
    cnt = session.get('counter', 0) + 1
    session.set('counter', cnt)
    return render(counter=cnt)

Data stored in the session needs to serializable using the Python pickle mechanism.

API Documentation

Error: Macro PythonDoc(trunk, diva.session) failed
Unsupported version control system "svn": No module named svn

Last modified 14 years ago Last modified on Nov 8, 2009, 12:15:19 PM