= 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 session data encoded as JSON, and is authenticated using [http://tools.ietf.org/html/rfc2104.html 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 [wiki:ApplicationObject#ApplicationContextVariables 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: {{{ #!python 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) }}} Because all session data is serialized to [http://json.org/ JSON] for transmission, only the basic data types supported by JSON are allowed: strings, integers, floats, and booleans, as well as lists and dictionaries. I consider this an advantage, as it forces you to decouple session data from the classes and data structures used in the application code. Also, the JSON serialization is often significantly more compact than e.g. `pickle`. == API Documentation == [[PythonDoc(trunk, diva.session)]]