cherrypy.lib.sessions

Session implementation for CherryPy.

You need to edit your config file to use sessions. Here’s an example:

[/]
tools.sessions.on = True
tools.sessions.storage_type = "file"
tools.sessions.storage_path = "/home/site/sessions"
tools.sessions.timeout = 60

This sets the session to be stored in files in the directory /home/site/sessions, and the session timeout to 60 minutes. If you omit storage_type the sessions will be saved in RAM. tools.sessions.on is the only required line for working sessions, the rest are optional.

By default, the session ID is passed in a cookie, so the client’s browser must have cookies enabled for your site.

To set data for the current session, use cherrypy.session['fieldname'] = 'fieldvalue'; to get data use cherrypy.session.get('fieldname').

Locking sessions

By default, the 'locking' mode of sessions is 'implicit', which means the session is locked early and unlocked late. Be mindful of this default mode for any requests that take a long time to process (streaming responses, expensive calculations, database lookups, API calls, etc), as other concurrent requests that also utilize sessions will hang until the session is unlocked.

If you want to control when the session data is locked and unlocked, set tools.sessions.locking = 'explicit'. Then call cherrypy.session.acquire_lock() and cherrypy.session.release_lock(). Regardless of which mode you use, the session is guaranteed to be unlocked when the request is complete.

Expiring Sessions

You can force a session to expire with cherrypy.lib.sessions.expire(). Simply call that function at the point you want the session to expire, and it will cause the session cookie to expire client-side.

Session Fixation Protection

If CherryPy receives, via a request cookie, a session id that it does not recognize, it will reject that id and create a new one to return in the response cookie. This helps prevent session fixation attacks. However, CherryPy “recognizes” a session id by looking up the saved session data for that id. Therefore, if you never save any session data, you will get a new session id for every request.

Sharing Sessions

If you run multiple instances of CherryPy (for example via mod_python behind Apache prefork), you most likely cannot use the RAM session backend, since each instance of CherryPy will have its own memory space. Use a different backend instead, and verify that all instances are pointing at the same file or db location. Alternately, you might try a load balancer which makes sessions “sticky”. Google is your friend, there.

Expiration Dates

The response cookie will possess an expiration date to inform the client at which point to stop sending the cookie back in requests. If the server time and client time differ, expect sessions to be unreliable. Make sure the system time of your server is accurate.

CherryPy defaults to a 60-minute session timeout, which also applies to the cookie which is sent to the client. Unfortunately, some versions of Safari (“4 public beta” on Windows XP at least) appear to have a bug in their parsing of the GMT expiration date–they appear to interpret the date as one hour in the past. Sixty minutes minus one hour is pretty close to zero, so you may experience this bug as a new session id for every request, unless the requests are less than one second apart. To fix, try increasing the session.timeout.

On the other extreme, some users report Firefox sending cookies after their expiration date, although this was on a system with an inaccurate system time. Maybe FF doesn’t trust system time.

Classes

class cherrypy.lib.sessions.Session(id=None, **kwargs)

A CherryPy dict-like Session object (one per request).

clean_freq = 5

The poll rate for expired session cleanup in minutes.

clean_thread = None

Class-level Monitor which calls self.clean_up.

clean_up()

Clean up expired sessions.

clear() → None. Remove all items from D.
debug = False

If True, log debug information.

delete()

Delete stored session data.

generate_id()

Return a new session id.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
has_key(k) → True if D has a key k, else False.
id

The current session ID.

id_observers = None

A list of callbacks to which to pass new id’s.

items() → list of D's (key, value) pairs, as 2-tuples.
keys() → list of D's keys.
load()

Copy stored session data into this session instance.

loaded = False

If True, data has been retrieved from storage. This should happen automatically on the first attempt to access session data.

locked = False

If True, this session instance has exclusive read/write access to session data.

missing = False

True if the session requested by the client did not exist.

now()

Generate the session specific concept of ‘now’.

Other session providers can override this to use alternative, possibly timezone aware, versions of ‘now’.

originalid = None

The session id passed by the client. May be missing or unsafe.

pop(key, default=False)

Remove the specified key and return the corresponding value. If key is not found, default is returned if given, otherwise KeyError is raised.

regenerate()

Replace the current session (with a new id).

regenerated = False

True if the application called session.regenerate(). This is not set by internal calls to regenerate the session id.

save()

Save session data.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D.
timeout = 60

Number of minutes after which to delete session data.

update(E) → None. Update D from E: for k in E: D[k] = E[k].
values() → list of D's values.
class cherrypy.lib.sessions.RamSession(id=None, **kwargs)
acquire_lock()

Acquire an exclusive lock on the currently-loaded session data.

clean_up()

Clean up expired sessions.

clear() → None. Remove all items from D.
delete()

Delete stored session data.

generate_id()

Return a new session id.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
has_key(k) → True if D has a key k, else False.
id

The current session ID.

items() → list of D's (key, value) pairs, as 2-tuples.
keys() → list of D's keys.
load()

Copy stored session data into this session instance.

now()

Generate the session specific concept of ‘now’.

Other session providers can override this to use alternative, possibly timezone aware, versions of ‘now’.

pop(key, default=False)

Remove the specified key and return the corresponding value. If key is not found, default is returned if given, otherwise KeyError is raised.

regenerate()

Replace the current session (with a new id).

release_lock()

Release the lock on the currently-loaded session data.

save()

Save session data.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D.
update(E) → None. Update D from E: for k in E: D[k] = E[k].
values() → list of D's values.
class cherrypy.lib.sessions.FileSession(id=None, **kwargs)

Implementation of the File backend for sessions

storage_path
The folder where session data will be saved. Each session will be saved as pickle.dump(data, expiration_time) in its own file; the filename will be self.SESSION_PREFIX + self.id.
lock_timeout
A timedelta or numeric seconds indicating how long to block acquiring a lock. If None (default), acquiring a lock will block indefinitely.
acquire_lock(path=None)

Acquire an exclusive lock on the currently-loaded session data.

clean_up()

Clean up expired sessions.

clear() → None. Remove all items from D.
delete()

Delete stored session data.

generate_id()

Return a new session id.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
has_key(k) → True if D has a key k, else False.
id

The current session ID.

items() → list of D's (key, value) pairs, as 2-tuples.
keys() → list of D's keys.
load()

Copy stored session data into this session instance.

now()

Generate the session specific concept of ‘now’.

Other session providers can override this to use alternative, possibly timezone aware, versions of ‘now’.

pop(key, default=False)

Remove the specified key and return the corresponding value. If key is not found, default is returned if given, otherwise KeyError is raised.

regenerate()

Replace the current session (with a new id).

release_lock(path=None)

Release the lock on the currently-loaded session data.

save()

Save session data.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D.
classmethod setup(**kwargs)

Set up the storage system for file-based sessions.

This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does).

update(E) → None. Update D from E: for k in E: D[k] = E[k].
values() → list of D's values.
class cherrypy.lib.sessions.PostgresqlSession(id=None, **kwargs)
Implementation of the PostgreSQL backend for sessions. It assumes

a table like this:

create table session (
    id varchar(40),
    data text,
    expiration_time timestamp
)

You must provide your own get_db function.

acquire_lock()

Acquire an exclusive lock on the currently-loaded session data.

clean_up()

Clean up expired sessions.

clear() → None. Remove all items from D.
delete()

Delete stored session data.

generate_id()

Return a new session id.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
has_key(k) → True if D has a key k, else False.
id

The current session ID.

items() → list of D's (key, value) pairs, as 2-tuples.
keys() → list of D's keys.
load()

Copy stored session data into this session instance.

now()

Generate the session specific concept of ‘now’.

Other session providers can override this to use alternative, possibly timezone aware, versions of ‘now’.

pop(key, default=False)

Remove the specified key and return the corresponding value. If key is not found, default is returned if given, otherwise KeyError is raised.

regenerate()

Replace the current session (with a new id).

release_lock()

Release the lock on the currently-loaded session data.

save()

Save session data.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D.
classmethod setup(**kwargs)

Set up the storage system for Postgres-based sessions.

This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does).

update(E) → None. Update D from E: for k in E: D[k] = E[k].
values() → list of D's values.
class cherrypy.lib.sessions.MemcachedSession(id=None, **kwargs)
acquire_lock()

Acquire an exclusive lock on the currently-loaded session data.

clean_up()

Clean up expired sessions.

clear() → None. Remove all items from D.
delete()

Delete stored session data.

generate_id()

Return a new session id.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
has_key(k) → True if D has a key k, else False.
id

The current session ID.

items() → list of D's (key, value) pairs, as 2-tuples.
keys() → list of D's keys.
load()

Copy stored session data into this session instance.

now()

Generate the session specific concept of ‘now’.

Other session providers can override this to use alternative, possibly timezone aware, versions of ‘now’.

pop(key, default=False)

Remove the specified key and return the corresponding value. If key is not found, default is returned if given, otherwise KeyError is raised.

regenerate()

Replace the current session (with a new id).

release_lock()

Release the lock on the currently-loaded session data.

save()

Save session data.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D.
classmethod setup(**kwargs)

Set up the storage system for memcached-based sessions.

This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does).

update(E) → None. Update D from E: for k in E: D[k] = E[k].
values() → list of D's values.

Functions

cherrypy.lib.sessions.save()

Save any changed session data.

cherrypy.lib.sessions.close()

Close the session object for this request.

cherrypy.lib.sessions.init(storage_type='ram', path=None, path_header=None, name='session_id', timeout=60, domain=None, secure=False, clean_freq=5, persistent=True, httponly=False, debug=False, **kwargs)

Initialize session object (using cookies).

storage_type
One of ‘ram’, ‘file’, ‘postgresql’, ‘memcached’. This will be used to look up the corresponding class in cherrypy.lib.sessions globals. For example, ‘file’ will use the FileSession class.
path
The ‘path’ value to stick in the response cookie metadata.
path_header
If ‘path’ is None (the default), then the response cookie ‘path’ will be pulled from request.headers[path_header].
name
The name of the cookie.
timeout
The expiration timeout (in minutes) for the stored session data. If ‘persistent’ is True (the default), this is also the timeout for the cookie.
domain
The cookie domain.
secure
If False (the default) the cookie ‘secure’ value will not be set. If True, the cookie ‘secure’ value will be set (to 1).
clean_freq (minutes)
The poll rate for expired session cleanup.
persistent
If True (the default), the ‘timeout’ argument will be used to expire the cookie. If False, the cookie will not have an expiry, and the cookie will be a “session cookie” which expires when the browser is closed.
httponly
If False (the default) the cookie ‘httponly’ value will not be set. If True, the cookie ‘httponly’ value will be set (to 1).

Any additional kwargs will be bound to the new Session instance, and may be specific to the storage type. See the subclass of Session you’re using for more information.

Set a response cookie for the client.

path
the ‘path’ value to stick in the response cookie metadata.
path_header
if ‘path’ is None (the default), then the response cookie ‘path’ will be pulled from request.headers[path_header].
name
the name of the cookie.
timeout
the expiration timeout for the cookie. If 0 or other boolean False, no ‘expires’ param will be set, and the cookie will be a “session cookie” which expires when the browser is closed.
domain
the cookie domain.
secure
if False (the default) the cookie ‘secure’ value will not be set. If True, the cookie ‘secure’ value will be set (to 1).
httponly
If False (the default) the cookie ‘httponly’ value will not be set. If True, the cookie ‘httponly’ value will be set (to 1).
cherrypy.lib.sessions.expire()

Expire the current session cookie.