Django provides full support for anonymous sessions. The session framework
lets you store and retrieve arbitrary data on a per-site-visitor basis. It
stores data on the server side and abstracts the sending and receiving of
cookies. Cookies contain a session ID – not the data itself (unless you’re
using the cookie based backend).

Edit the MIDDLEWARE_CLASSES setting and make sure
it contains 'django.contrib.sessions.middleware.SessionMiddleware'.
The default settings.py created by django-admin.pystartproject
has SessionMiddleware activated.

If you don’t want to use sessions, you might as well remove the
SessionMiddleware line from MIDDLEWARE_CLASSES and
'django.contrib.sessions' from your INSTALLED_APPS.
It’ll save you a small bit of overhead.

By default, Django stores sessions in your database (using the model
django.contrib.sessions.models.Session). Though this is convenient, in
some setups it’s faster to store session data elsewhere, so Django can be
configured to store session data on your filesystem or in your cache.

For better performance, you may want to use a cache-based session backend.

To store session data using Django’s cache system, you’ll first need to make
sure you’ve configured your cache; see the cache documentation for details.

Warning

You should only use cache-based sessions if you’re using the Memcached
cache backend. The local-memory cache backend doesn’t retain data long
enough to be a good choice, and it’ll be faster to use file or database
sessions directly instead of sending everything through the file or
database cache backends.

Once your cache is configured, you’ve got two choices for how to store data in
the cache:

Set SESSION_ENGINE to
"django.contrib.sessions.backends.cache" for a simple caching session
store. Session data will be stored directly your cache. However, session
data may not be persistent: cached data can be evicted if the cache fills
up or if the cache server is restarted.

For persistent, cached data, set SESSION_ENGINE to
"django.contrib.sessions.backends.cached_db". This uses a
write-through cache – every write to the cache will also be written to
the database. Session reads only use the database if the data is not
already in the cache.

Both session stores are quite fast, but the simple cache is faster because it
disregards persistence. In most cases, the cached_db backend will be fast
enough, but if you need that last bit of performance, and are willing to let
session data be expunged from time to time, the cache backend is for you.

To use file-based sessions, set the SESSION_ENGINE setting to
"django.contrib.sessions.backends.file".

You might also want to set the SESSION_FILE_PATH setting (which
defaults to output from tempfile.gettempdir(), most likely /tmp) to
control where Django stores session files. Be sure to check that your Web
server has permissions to read and write to this location.

It’s recommended to leave the SESSION_COOKIE_HTTPONLY setting
on True to prevent access to the stored data from JavaScript.

Warning

The session data is signed but not encrypted

When using the cookies backend the session data can be read by the client.

A MAC (Message Authentication Code) is used to protect the data against
changes by the client, so that the session data will be invalidated when being
tampered with. The same invalidation happens if the client storing the
cookie (e.g. your user’s browser) can’t store all of the session cookie and
drops data. Even though Django compresses the data, it’s still entirely
possible to exceed the common limit of 4096 bytes per cookie.

No freshness guarantee

Note also that while the MAC can guarantee the authenticity of the data
(that it was generated by your site, and not someone else), and the
integrity of the data (that it is all there and correct), it cannot
guarantee freshness i.e. that you are being sent back the last thing you
sent to the client. This means that for some uses of session data, the
cookie backend might open you up to replay attacks. Cookies will only be
detected as ‘stale’ if they are older than your
SESSION_COOKIE_AGE.

Delete the current session data from the session and regenerate the
session key value that is sent back to the user in the cookie. This is
used if you want to ensure that the previous session data can’t be
accessed again from the user’s browser (for example, the
django.contrib.auth.logout() function calls it).

Sets a test cookie to determine whether the user’s browser supports
cookies. Due to the way cookies work, you won’t be able to test this
until the user’s next page request. See Setting test cookies below for
more information.

Returns either True or False, depending on whether the user’s
browser accepted the test cookie. Due to the way cookies work, you’ll
have to call set_test_cookie() on a previous, separate page request.
See Setting test cookies below for more information.

The standard django.contrib.auth.logout() function actually does a bit
more than this to prevent inadvertent data leakage. It calls the
flush() method of request.session.
We are using this example as a demonstration of how to work with session
objects, not as a full logout() implementation.

As a convenience, Django provides an easy way to test whether the user’s
browser accepts cookies. Just call the
set_test_cookie() method of
request.session in a view, and call
test_cookie_worked() in a subsequent view –
not in the same view call.

This awkward split between set_test_cookie() and test_cookie_worked()
is necessary due to the way cookies work. When you set a cookie, you can’t
actually tell whether a browser accepted it until the browser’s next request.

It’s good practice to use
delete_test_cookie() to clean up after
yourself. Do this after you’ve verified that the test cookie worked.

If you’re using the django.contrib.sessions.backends.db backend, each
session is just a normal Django model. The Session model is defined in
django/contrib/sessions/models.py. Because it’s a normal model, you can
access sessions using the normal Django database API:

By default, Django only saves to the session database when the session has been
modified – that is if any of its dictionary values have been assigned or
deleted:

# Session is modified.request.session['foo']='bar'# Session is modified.delrequest.session['foo']# Session is modified.request.session['foo']={}# Gotcha: Session is NOT modified, because this alters# request.session['foo'] instead of request.session.request.session['foo']['bar']='baz'

In the last case of the above example, we can tell the session object
explicitly that it has been modified by setting the modified attribute on
the session object:

request.session.modified=True

To change this default behavior, set the SESSION_SAVE_EVERY_REQUEST
setting to True. When set to True, Django will save the session to the
database on every single request.

Note that the session cookie is only sent when a session has been created or
modified. If SESSION_SAVE_EVERY_REQUEST is True, the session
cookie will be sent on every request.

Similarly, the expires part of a session cookie is updated each time the
session cookie is sent.

If SESSION_EXPIRE_AT_BROWSER_CLOSE is set to True, Django will
use browser-length cookies – cookies that expire as soon as the user closes
his or her browser. Use this if you want people to have to log in every time
they open a browser.

This setting is a global default and can be overwritten at a per-session level
by explicitly calling the set_expiry() method
of request.session as described above in using sessions in views.

If you’re using the database backend, note that session data can accumulate in
the django_session database table and Django does not provide automatic
purging. Therefore, it’s your job to purge expired sessions on a regular basis.

To understand this problem, consider what happens when a user uses a session.
When a user logs in, Django adds a row to the django_session database
table. Django updates this row each time the session data changes. If the user
logs out manually, Django deletes the row. But if the user does not log out,
the row never gets deleted.

Django provides a sample clean-up script: django-admin.pycleanup.
That script deletes any session in the session table whose expire_date is
in the past – but your application may have different requirements.

Whether to use HTTPOnly flag on the session cookie. If this is set to
True, client-side JavaScript will not to be able to access the
session cookie.

HTTPOnly is a flag included in a Set-Cookie HTTP response header. It
is not part of the RFC 2109 standard for cookies, and it isn’t honored
consistently by all browsers. However, when it is honored, it can be a
useful way to mitigate the risk of client side script accessing the
protected cookie data.

Changed in Django 1.4: The default value of the setting was changed from False to True.

Whether to use a secure cookie for the session cookie. If this is set to
True, the cookie will be marked as “secure,” which means browsers may
ensure that the cookie is only sent under an HTTPS connection.

Whether to save the session data on every request. If this is False
(default), then the session data will only be saved if it has been modified –
that is, if any of its dictionary values have been assigned or deleted.

The Django sessions framework is entirely, and solely, cookie-based. It does
not fall back to putting session IDs in URLs as a last resort, as PHP does.
This is an intentional design decision. Not only does that behavior make URLs
ugly, it makes your site vulnerable to session-ID theft via the “Referer”
header.