# Session Management

CherryPy 2.1 includes a powerful sessions system provided via a new `sessionFilter`.

## Using Sessions

First you need to enable the session filter through the configuration system, by setting `sessionFilter.on` to `True`. This gives you a variable called `cherrypy.session`, which is a dictionary-like object where you can read/store your session data. This dictionary always has a special key called `_id` which contains the session id.

Here is sample code showing how to implement a simple counter using sessions:

Basic example of session usage

                import cherrypy
                class Root:
                    def index(self):
                        count = cherrypy.session.get('count', 0) + 1
                        cherrypy.session['count'] = count
                        return 'Counter: %s' % count
                    index.exposed = True

                cherrypy.config.update({'sessionFilter.on': True})
                cherrypy.root = Root()
                cherrypy.server.start()

## Configuring sessions

The following configuration options are available for "sessionFilter":

- `sessionFilter.on`: `True` or `False` (default): enable/disable sessions

- `sessionFilter.storageType`: Specify which storage type should be used for storing session data on the server. Built-in types are `Ram` (default), `File` and `PostgreSQL` (see for more info).

- `sessionFilter.storagePath`: Specifies the directory in which CherryPy puts the session files when sessionFilter.storageType is set to `File`.

- `sessionFilter.timeout`: The number of minutes of inactivity before an individual session can be removed. It can be a float (ex: 0.5 for 30 seconds). Defaults to 60.

- `sessionFilter.cleanUpDelay`: Once in a while the server cleans up old/expired sessions. This config option specifies how often this clean up process should happen. The delay is in minutes. Defaults to 5.

- `sessionFilter.cookieName`: The name of the cookie that CherryPy will use to store the session ID. Defaults to `sessionID`.

- `sessionFilter.getDB`: See the `PostgreSQL` backend from .

- `sessionFilter.deadlockTimeout`: See .

- `sessionFilter.onCreateSession`: See .

- `sessionFilter.onDeleteSession`: See .

- `sessionFilter.storageClass`: See .

## Choosing the backend

CherryPy comes with multiple build-in backends for storing session data on the server side. They are:

- `Ram`: All data is stored in RAM; this is the fastest storage, but it means that the data will be lost if you restart the server; and it also means that it won't scale to multiple processes/machines

- `File`: All data is stored on disk; this is a bit slower than Ram storage, but the data will persist if you restart the server. It also means that data can be shared amongst multiple CherryPy processes, either on the same machine, or on multiple machines if all machines have access to the same disk (for example, via NFS).

- `PostgreSQL`: This backend is included with CherryPy to show how easy it is to implement your own custom backend for the session system. All data is stored in a PostgreSQL database; storing your data in a database is the recommend setup for production if you have a very high traffic website and you need to scale your site across multiple machines. To use this backend, you'll need to create the following table in your PostgreSQL database:

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

  You also need to programmatically set the `sessionFilter.getDB` config option to a function that returns a DB connection.

Note that when using the `Ram` backend, the session data is saved as soon as you stick it in `cherrypy.session`. So even if an error occurs later on in the page handler the data is still saved; this is not the case for the other backends.

## Writing your own custom backend

By default, CherryPy comes with 3 built-in backends, but if you have specific needs, it is very easy to implement your own custom backend (for instance, another database, or an XML-RPC server, ...). To do so, all you have to do is write a class that implements the following methods:

                class MyCustomBackend:
                    def save(self, id, data, expirationTime):
                        """ Save the session data and expirationTime for that session id """
                    def load(self, id):
                        """ Load the session data and expirationTime for 'id' and return
                            a tuple (data, expirationTime) (even if the session is
                            expired). Return None if id doesn't exist. """
                    def cleanUp(self):
                        """ Delete expired session data from storage and call
                            'onDeleteSession' for each deleted session id """

Note that if you want to use `explicit` locking (see ), you also have to implement two extra methods: `acquireLock` and `releaseLock`.

Once you have written this class, you have to programmatically set the `sessionFilter.storageClass` config option to this class.

If you need help in writing your own custom backend it is a good idea to look at how the current ones (ram, file and postgresql) are implemented. They are implemented in the file `cherrypy/lib/filter/sessionfilter.py`

## Handling concurrent requests for the same session data

It is normally quite rare to have two simultaneous requests with the same session ID. It means that a same browser is making 2 requests to your server at the same time (to dynamic pages ... static data like images don't have sessions). However, this case can happen (if you're using frames for instance), and it will happen more and more often as more and more people start using Ajax.

In that case, we need to make sure that access to the session data is serialized. This way, threads can't both modify the data at the same time and leave it in an inconsistent state.

You can easily make CherryPy serialize access to the session data by setting the `sessionFilter.locking` config option to `implicit` (the default is `explicit`, which means that CherryPy won't do any locking for you). In the `implicit` mode, if a browser makes a second request while a first request is still being handled by the server, the second request will block while the first request is accessing the data. As soon as the first request is finished then the second request will be able to access it.

This means that the second request will block until the first request is finished.

## Being notified when sessions are created/deleted

It is possible to configure the `sessionFilter` so that it calls some special callback functions from your code when sessions are being created/deleted. To do so you have to set the `sessionFilter.onCreateSession` and `sessionFilter.onDeleteSession` config options. When a session is created/deleted, CherryPy will call these functions and pass them the session data.