4.8.1 Classes

Session( req[, sid, secret, timeout, lock])

Session() takes the same arguments as BaseSession.

This function returns a instance of the default session class. The session class to be used can be specified using PythonOption mod_python.session.session_type value, where value is one of DbmSession, MemorySession or FileSession. Specifying custom session classes using PythonOption session is not yet supported.

If session type option is not found, the function queries the MPM and based on that returns either a new instance of DbmSession or MemorySession. MemorySession will be used if the MPM is threaded and not forked (such is the case on Windows), or if it threaded, forked, but only one process is allowed (the worker MPM can be configured to run this way). In all other cases DbmSession is used.

Note that on Windows if you are using multiple Python interpreter instances and you need sessions to be shared between applications running within the context of the distinct Python interpreter instances, you must specifically indicate that DbmSession should be used, as MemorySession will only allow a session to be valid within the context of the same Python interpreter instance.

Also note that the option name mod_python.session.session_type only started to be used from mod_python 3.3 onwards. If you need to retain compatability with older versions of mod_python, you should use the now obsolete session option instead.

class BaseSession( req[, sid, secret, timeout, lock])

This class is meant to be used as a base class for other classes that implement a session storage mechanism. req is a required reference to a mod_python request object.

BaseSession is a subclass of dict. Data can be stored and retrieved from the session by using it as a dictionary.

sid is an optional session id; if provided, such a session must already exist, otherwise it is ignored and a new session with a new sid is created. If sid is not provided, the object will attempt to look at cookies for session id. If a sid is found in cookies, but it is not previously known or the session has expired, then a new sid is created. Whether a session is ``new'' can be determined by calling the is_new() method.

Cookies generated by sessions will have a path attribute which is calculated by comparing the server DocumentRoot and the directory in which the PythonHandler directive currently in effect was specified. E.g. if document root is /a/b/c and the directory PythonHandler was specified was /a/b/c/d/e, the path will be set to /d/e.

The deduction of the path in this way will only work though where the Directory directive is used and the directory is actually within the document root. If the Location directive is used or the directory is outside of the document root, the path will be set to /. You can force a specific path by setting the mod_python.session.application_path option ("PythonOption mod_python.session.application_path /my/path" in server configuration).

Note that prior to mod_python 3.3, the option was ApplicationPath. If your system needs to be compatible with older versions of mod_python, you should continue to use the now obsolete option name.

The domain of a cookie is by default not set for a session and as such the session is only valid for the host which generated it. In order to have a session which spans across common sub domains, you can specify the parent domain using the mod_python.session.application_domain option ("PythonOption mod_python.session.application_domain mod_python.org" in server configuration).

When a secret is provided, BaseSession will use SignedCookie when generating cookies thereby making the session id almost impossible to fake. The default is to use plain Cookie (though even if not signed, the session id is generated to be very difficult to guess).

A session will timeout if it has not been accessed and a save performed, within the timeout period. Upon a save occuring the time of last access is updated and the period until the session will timeout be reset. The default timeout period is 30 minutes. An attempt to load an expired session will result in a ``new'' session.

The lock argument (defaults to 1) indicates whether locking should be used. When locking is on, only one session object with a particular session id can be instantiated at a time.

A session is in ``new'' state when the session id was just generated, as opposed to being passed in via cookies or the sid argument.

is_new( )
Returns 1 if this session is new. A session will also be ``new'' after an attempt to instantiate an expired or non-existent session. It is important to use this method to test whether an attempt to instantiate a session has succeeded, e.g.:
sess = Session(req)
if sess.is_new():
    # redirect to login
    util.redirect(req, 'http://www.mysite.com/login')

id( )
Returns the session id.

created( )
Returns the session creation time in seconds since beginning of epoch.

last_accessed( )
Returns last access time in seconds since beginning of epoch.

timeout( )
Returns session timeout interval in seconds.

set_timeout( secs)
Set timeout to secs.

invalidate( )
This method will remove the session from the persistent store and also place a header in outgoing headers to invalidate the session id cookie.

load( )
Load the session values from storage.

save( )
This method writes session values to storage.

delete( )
Remove the session from storage.

init_lock( )
This method initializes the session lock. There is no need to ever call this method, it is intended for subclasses that wish to use an alternative locking mechanism.

lock( )
Locks this session. If the session is already locked by another thread/process, wait until that lock is released. There is no need to call this method if locking is handled automatically (default).

This method registeres a cleanup which always unlocks the session at the end of the request processing.

unlock( )
Unlocks this session. (Same as lock() - when locking is handled automatically (default), there is no need to call this method).

cleanup( )
This method is for subclasses to implement session storage cleaning mechanism (i.e. deleting expired sessions, etc.). It will be called at random, the chance of it being called is controlled by CLEANUP_CHANCE Session module variable (default 1000). This means that cleanups will be ordered at random and there is 1 in 1000 chance of it happening. Subclasses implementing this method should not perform the (potentially time consuming) cleanup operation in this method, but should instead use req.register_cleanup to register a cleanup which will be executed after the request has been processed.

class DbmSession( req, [, dbm, sid, secret, dbmtype, timeout, lock])

This class provides session storage using a dbm file. Generally, dbm access is very fast, and most dbm implementations memory-map files for faster access, which makes their performance nearly as fast as direct shared memory access.

dbm is the name of the dbm file (the file must be writable by the httpd process). This file is not deleted when the server process is stopped (a nice side benefit of this is that sessions can survive server restarts). By default the session information is stored in a dbmfile named mp_sess.dbm and stored in a temporary directory returned by tempfile.gettempdir() standard library function. An alternative directory can be specified using PythonOption mod_python.dbm_session.database_directory /path/to/directory. The path and filename can can be overridden by setting PythonOption mod_python.dbm_session.database_filename filename.

Note that the above names for the PythonOption settings were changed to these values in mod_python 3.3. If you need to retain compatability with older versions of mod_python, you should continue to use the now obsolete session_directory and session_dbm options.

The implementation uses Python anydbm module, which will default to dbhash on most systems. If you need to use a specific dbm implementation (e.g. gdbm), you can pass that module as dbmtype.

Note that using this class directly is not cross-platform. For best compatibility across platforms, always use the Session() function to create sessions.

class FileSession( req, [, sid, secret, timeout, lock, fast_cleanup, verify_cleanup])

New in version 3.2.0.

This class provides session storage using a separate file for each session. It is a subclass of BaseSession.

Session data is stored in a separate file for each session. These files are not deleted when the server process is stopped, so sessions are persistent across server restarts. The session files are saved in a directory named mp_sess in the temporary directory returned by the tempfile.gettempdir() standard library function. An alternate path can be set using PythonOption mod_python.file_session.database_directory /path/to/directory. This directory must exist and be readable and writeable by the apache process.

Note that the above name for the PythonOption setting was changed to these values in mod_python 3.3. If you need to retain compatability with older versions of mod_python, you should continue to use the now obsolete session_directory option.

Expired session files are periodically removed by the cleanup mechanism. The behaviour of the cleanup can be controlled using the fast_cleanup and verify_cleanup parameters, as well as PythonOption mod_python.file_session.cleanup_time_limit and PythonOption mod_python.file_session.cleanup_grace_period.

class MemorySession( req, [, sid, secret, timeout, lock])

This class provides session storage using a global dictionary. This class provides by far the best performance, but cannot be used in a multi-process configuration, and also consumes memory for every active session. It also cannot be used where multiple Python interpreters are used within the one Apache process and it is necessary to share sessions between applications running in the distinct interpreters.

Note that using this class directly is not cross-platform. For best compatibility across platforms, always use the Session() function to create sessions.