2005-08-17 06:00:02 +02:00
|
|
|
===================
|
|
|
|
How to use sessions
|
|
|
|
===================
|
|
|
|
|
2009-06-18 15:32:12 +02:00
|
|
|
.. module:: django.contrib.sessions
|
|
|
|
:synopsis: Provides session management for Django projects.
|
|
|
|
|
2011-06-26 19:00:24 +02:00
|
|
|
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 :ref:`cookie based backend<cookie-session-backend>`).
|
2005-08-17 06:00:02 +02:00
|
|
|
|
|
|
|
Enabling sessions
|
|
|
|
=================
|
|
|
|
|
2010-08-19 21:27:44 +02:00
|
|
|
Sessions are implemented via a piece of :doc:`middleware </ref/middleware>`.
|
2005-08-17 06:00:02 +02:00
|
|
|
|
2007-09-15 23:29:14 +02:00
|
|
|
To enable session functionality, do the following:
|
2005-08-17 06:00:02 +02:00
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* Edit the :setting:`MIDDLEWARE_CLASSES` setting and make sure
|
|
|
|
it contains ``'django.contrib.sessions.middleware.SessionMiddleware'``.
|
|
|
|
The default ``settings.py`` created by ``django-admin.py startproject``
|
|
|
|
has ``SessionMiddleware`` activated.
|
2007-09-16 00:36:53 +02:00
|
|
|
|
2005-08-17 06:00:02 +02:00
|
|
|
If you don't want to use sessions, you might as well remove the
|
2011-05-29 19:41:04 +02:00
|
|
|
``SessionMiddleware`` line from :setting:`MIDDLEWARE_CLASSES` and
|
2011-05-20 02:51:25 +02:00
|
|
|
``'django.contrib.sessions'`` from your :setting:`INSTALLED_APPS`.
|
|
|
|
It'll save you a small bit of overhead.
|
2005-08-17 06:00:02 +02:00
|
|
|
|
2007-09-15 23:29:14 +02:00
|
|
|
Configuring the session engine
|
|
|
|
==============================
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
2009-12-22 16:18:51 +01:00
|
|
|
Using database-backed sessions
|
|
|
|
------------------------------
|
|
|
|
|
|
|
|
If you want to use a database-backed session, you need to add
|
2011-05-29 19:41:04 +02:00
|
|
|
``'django.contrib.sessions'`` to your :setting:`INSTALLED_APPS` setting.
|
2009-12-22 16:18:51 +01:00
|
|
|
|
|
|
|
Once you have configured your installation, run ``manage.py syncdb``
|
|
|
|
to install the single database table that stores session data.
|
|
|
|
|
2009-01-10 23:18:14 +01:00
|
|
|
Using cached sessions
|
|
|
|
---------------------
|
|
|
|
|
|
|
|
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
|
2010-08-19 21:27:44 +02:00
|
|
|
sure you've configured your cache; see the :doc:`cache documentation
|
|
|
|
</topics/cache>` for details.
|
2009-01-10 23:18:14 +01:00
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
2009-01-11 06:47:06 +01:00
|
|
|
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.
|
2009-01-10 23:18:14 +01:00
|
|
|
|
2009-01-11 06:47:06 +01:00
|
|
|
Once your cache is configured, you've got two choices for how to store data in
|
2009-01-10 23:18:14 +01:00
|
|
|
the cache:
|
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* Set :setting:`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.
|
2009-01-10 23:18:14 +01:00
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* For persistent, cached data, set :setting:`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.
|
2009-01-10 23:18:14 +01:00
|
|
|
|
|
|
|
Both session stores are quite fast, but the simple cache is faster because it
|
2009-01-11 06:47:06 +01:00
|
|
|
disregards persistence. In most cases, the ``cached_db`` backend will be fast
|
2009-01-10 23:18:14 +01:00
|
|
|
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.
|
|
|
|
|
2009-12-22 16:18:51 +01:00
|
|
|
If you use the ``cached_db`` session backend, you also need to follow the
|
|
|
|
configuration instructions for the `using database-backed sessions`_.
|
|
|
|
|
2007-09-15 23:29:14 +02:00
|
|
|
Using file-based sessions
|
|
|
|
-------------------------
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
To use file-based sessions, set the :setting:`SESSION_ENGINE` setting to
|
2007-09-15 23:29:14 +02:00
|
|
|
``"django.contrib.sessions.backends.file"``.
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
You might also want to set the :setting:`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.
|
2007-09-15 23:29:14 +02:00
|
|
|
|
2011-06-26 19:00:24 +02:00
|
|
|
.. _cookie-session-backend:
|
|
|
|
|
|
|
|
Using cookie-based sessions
|
|
|
|
---------------------------
|
|
|
|
|
|
|
|
.. versionadded:: 1.4
|
|
|
|
|
|
|
|
To use cookies-based sessions, set the :setting:`SESSION_ENGINE` setting to
|
2011-11-17 22:16:42 +01:00
|
|
|
``"django.contrib.sessions.backends.signed_cookies"``. The session data will be
|
2011-06-26 19:00:24 +02:00
|
|
|
stored using Django's tools for :doc:`cryptographic signing </topics/signing>`
|
|
|
|
and the :setting:`SECRET_KEY` setting.
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
2011-11-21 23:03:03 +01:00
|
|
|
It's recommended to leave the :setting:`SESSION_COOKIE_HTTPONLY` setting
|
|
|
|
``True`` to prevent tampering of the stored data from JavaScript.
|
2011-06-26 19:00:24 +02:00
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
2011-10-17 17:43:24 +02:00
|
|
|
**The session data is signed but not encrypted**
|
2011-06-26 19:00:24 +02:00
|
|
|
|
2011-10-17 17:43:24 +02:00
|
|
|
When using the cookies backend the session data can be read by the client.
|
2011-06-26 19:00:24 +02:00
|
|
|
|
2011-10-17 17:43:24 +02:00
|
|
|
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
|
2011-10-17 17:52:01 +02:00
|
|
|
cookie backend might open you up to `replay attacks`_. Cookies will only be
|
2011-10-17 17:43:24 +02:00
|
|
|
detected as 'stale' if they are older than your
|
|
|
|
:setting:`SESSION_COOKIE_AGE`.
|
|
|
|
|
|
|
|
**Performance**
|
|
|
|
|
|
|
|
Finally, the size of a cookie can have an impact on the `speed of your site`_.
|
2011-06-26 19:00:24 +02:00
|
|
|
|
|
|
|
.. _`common limit of 4096 bytes`: http://tools.ietf.org/html/rfc2965#section-5.3
|
2011-10-17 17:43:24 +02:00
|
|
|
.. _`replay attacks`: http://en.wikipedia.org/wiki/Replay_attack
|
2011-06-26 19:00:24 +02:00
|
|
|
.. _`speed of your site`: http://yuiblog.com/blog/2007/03/01/performance-research-part-3/
|
2009-12-22 16:18:51 +01:00
|
|
|
|
2005-08-17 06:00:02 +02:00
|
|
|
Using sessions in views
|
|
|
|
=======================
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
When ``SessionMiddleware`` is activated, each :class:`~django.http.HttpRequest`
|
|
|
|
object -- the first argument to any Django view function -- will have a
|
|
|
|
``session`` attribute, which is a dictionary-like object.
|
2005-08-17 06:00:02 +02:00
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
You can read it and write to ``request.session`` at any point in your view.
|
|
|
|
You can edit it multiple times.
|
2005-08-17 06:00:02 +02:00
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. class:: backends.base.SessionBase
|
|
|
|
|
|
|
|
This is the base class for all session objects. It has the following
|
|
|
|
standard dictionary methods:
|
|
|
|
|
|
|
|
.. method:: __getitem__(key)
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2005-08-17 06:00:02 +02:00
|
|
|
Example: ``fav_color = request.session['fav_color']``
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: __setitem__(key, value)
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2005-08-17 06:00:02 +02:00
|
|
|
Example: ``request.session['fav_color'] = 'blue'``
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: __delitem__(key)
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2005-11-20 18:16:13 +01:00
|
|
|
Example: ``del request.session['fav_color']``. This raises ``KeyError``
|
|
|
|
if the given ``key`` isn't already in the session.
|
2005-08-17 06:00:02 +02:00
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: __contains__(key)
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2006-05-02 03:31:56 +02:00
|
|
|
Example: ``'fav_color' in request.session``
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: get(key, default=None)
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2005-08-17 06:00:02 +02:00
|
|
|
Example: ``fav_color = request.session.get('fav_color', 'red')``
|
|
|
|
|
2011-08-20 21:22:34 +02:00
|
|
|
.. method:: pop(key)
|
|
|
|
|
|
|
|
Example: ``fav_color = request.session.pop('fav_color')``
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: keys
|
2006-02-10 22:33:07 +01:00
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: items
|
2006-02-10 22:33:07 +01:00
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: setdefault
|
2007-12-02 16:27:29 +01:00
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: clear
|
2008-09-02 05:40:42 +02:00
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
It also has these methods:
|
2005-08-17 06:00:02 +02:00
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: flush
|
2008-08-14 05:57:46 +02:00
|
|
|
|
2009-05-26 07:29:28 +02:00
|
|
|
Delete the current session data from the session and regenerate the
|
2008-08-14 05:57:46 +02:00
|
|
|
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
|
2008-08-14 05:58:00 +02:00
|
|
|
accessed again from the user's browser (for example, the
|
2009-02-16 06:10:31 +01:00
|
|
|
:func:`django.contrib.auth.logout()` function calls it).
|
2008-08-14 05:57:46 +02:00
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: set_test_cookie
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2005-08-17 06:00:02 +02:00
|
|
|
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
|
2008-06-16 06:01:33 +02:00
|
|
|
until the user's next page request. See `Setting test cookies`_ below for
|
2005-08-17 06:00:02 +02:00
|
|
|
more information.
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: test_cookie_worked
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2005-08-17 06:00:02 +02:00
|
|
|
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.
|
2008-06-16 06:01:33 +02:00
|
|
|
See `Setting test cookies`_ below for more information.
|
2005-08-17 06:00:02 +02:00
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: delete_test_cookie
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2005-09-23 03:28:44 +02:00
|
|
|
Deletes the test cookie. Use this to clean up after yourself.
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: set_expiry(value)
|
2008-06-07 22:28:06 +02:00
|
|
|
|
|
|
|
Sets the expiration time for the session. You can pass a number of
|
|
|
|
different values:
|
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* If ``value`` is an integer, the session will expire after that
|
|
|
|
many seconds of inactivity. For example, calling
|
|
|
|
``request.session.set_expiry(300)`` would make the session expire
|
|
|
|
in 5 minutes.
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* If ``value`` is a ``datetime`` or ``timedelta`` object, the
|
|
|
|
session will expire at that specific date/time.
|
2008-06-12 05:36:48 +02:00
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* If ``value`` is ``0``, the user's session cookie will expire
|
|
|
|
when the user's Web browser is closed.
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* If ``value`` is ``None``, the session reverts to using the global
|
|
|
|
session expiry policy.
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2010-05-06 03:35:02 +02:00
|
|
|
Reading a session is not considered activity for expiration
|
|
|
|
purposes. Session expiration is computed from the last time the
|
|
|
|
session was *modified*.
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: get_expiry_age
|
2008-06-07 22:28:06 +02:00
|
|
|
|
|
|
|
Returns the number of seconds until this session expires. For sessions
|
|
|
|
with no custom expiration (or those set to expire at browser close), this
|
2011-05-20 02:51:25 +02:00
|
|
|
will equal :setting:`SESSION_COOKIE_AGE`.
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: get_expiry_date
|
2008-06-07 22:28:06 +02:00
|
|
|
|
|
|
|
Returns the date this session will expire. For sessions with no custom
|
|
|
|
expiration (or those set to expire at browser close), this will equal the
|
2011-05-20 02:51:25 +02:00
|
|
|
date :setting:`SESSION_COOKIE_AGE` seconds from now.
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
.. method:: get_expire_at_browser_close
|
2008-06-07 22:28:06 +02:00
|
|
|
|
|
|
|
Returns either ``True`` or ``False``, depending on whether the user's
|
2008-06-12 05:36:48 +02:00
|
|
|
session cookie will expire when the user's Web browser is closed.
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2005-08-17 06:05:42 +02:00
|
|
|
Session object guidelines
|
|
|
|
-------------------------
|
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* Use normal Python strings as dictionary keys on ``request.session``. This
|
|
|
|
is more of a convention than a hard-and-fast rule.
|
2005-08-17 06:05:42 +02:00
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* Session dictionary keys that begin with an underscore are reserved for
|
|
|
|
internal use by Django.
|
2005-08-17 06:05:42 +02:00
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* Don't override ``request.session`` with a new object, and don't access or
|
|
|
|
set its attributes. Use it like a Python dictionary.
|
2005-08-17 06:05:42 +02:00
|
|
|
|
2005-08-17 06:00:02 +02:00
|
|
|
Examples
|
|
|
|
--------
|
|
|
|
|
|
|
|
This simplistic view sets a ``has_commented`` variable to ``True`` after a user
|
|
|
|
posts a comment. It doesn't let a user post a comment more than once::
|
|
|
|
|
|
|
|
def post_comment(request, new_comment):
|
|
|
|
if request.session.get('has_commented', False):
|
|
|
|
return HttpResponse("You've already commented.")
|
|
|
|
c = comments.Comment(comment=new_comment)
|
|
|
|
c.save()
|
|
|
|
request.session['has_commented'] = True
|
|
|
|
return HttpResponse('Thanks for your comment!')
|
|
|
|
|
2005-11-13 05:43:07 +01:00
|
|
|
This simplistic view logs in a "member" of the site::
|
2005-08-17 06:00:02 +02:00
|
|
|
|
|
|
|
def login(request):
|
2007-05-03 00:10:12 +02:00
|
|
|
m = Member.objects.get(username=request.POST['username'])
|
2005-11-13 05:43:07 +01:00
|
|
|
if m.password == request.POST['password']:
|
|
|
|
request.session['member_id'] = m.id
|
2005-08-17 06:00:02 +02:00
|
|
|
return HttpResponse("You're logged in.")
|
|
|
|
else:
|
|
|
|
return HttpResponse("Your username and password didn't match.")
|
|
|
|
|
2005-11-13 05:43:07 +01:00
|
|
|
...And this one logs a member out, according to ``login()`` above::
|
2005-08-17 06:00:02 +02:00
|
|
|
|
|
|
|
def logout(request):
|
|
|
|
try:
|
2005-11-13 05:43:07 +01:00
|
|
|
del request.session['member_id']
|
2005-08-17 06:00:02 +02:00
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
return HttpResponse("You're logged out.")
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
The standard :meth:`django.contrib.auth.logout` function actually does a bit
|
|
|
|
more than this to prevent inadvertent data leakage. It calls the
|
|
|
|
:meth:`~backends.base.SessionBase.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.
|
2008-08-14 05:58:00 +02:00
|
|
|
|
2005-08-17 06:00:02 +02:00
|
|
|
Setting test cookies
|
|
|
|
====================
|
|
|
|
|
|
|
|
As a convenience, Django provides an easy way to test whether the user's
|
2011-05-20 02:51:25 +02:00
|
|
|
browser accepts cookies. Just call the
|
|
|
|
:meth:`~backends.base.SessionBase.set_test_cookie` method of
|
|
|
|
``request.session`` in a view, and call
|
|
|
|
:meth:`~backends.base.SessionBase.test_cookie_worked` in a subsequent view --
|
2005-08-17 06:00:02 +02:00
|
|
|
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.
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
It's good practice to use
|
|
|
|
:meth:`~backends.base.SessionBase.delete_test_cookie()` to clean up after
|
|
|
|
yourself. Do this after you've verified that the test cookie worked.
|
2005-09-23 03:28:44 +02:00
|
|
|
|
2005-08-17 06:00:02 +02:00
|
|
|
Here's a typical usage example::
|
|
|
|
|
|
|
|
def login(request):
|
2006-11-27 01:08:46 +01:00
|
|
|
if request.method == 'POST':
|
2005-08-17 06:00:02 +02:00
|
|
|
if request.session.test_cookie_worked():
|
2005-09-23 03:28:44 +02:00
|
|
|
request.session.delete_test_cookie()
|
2005-08-17 06:00:02 +02:00
|
|
|
return HttpResponse("You're logged in.")
|
|
|
|
else:
|
|
|
|
return HttpResponse("Please enable cookies and try again.")
|
|
|
|
request.session.set_test_cookie()
|
2006-05-02 03:31:56 +02:00
|
|
|
return render_to_response('foo/login_form.html')
|
2005-08-17 06:00:02 +02:00
|
|
|
|
|
|
|
Using sessions out of views
|
|
|
|
===========================
|
|
|
|
|
2007-09-16 00:36:53 +02:00
|
|
|
An API is available to manipulate session data outside of a view::
|
2007-09-15 23:29:14 +02:00
|
|
|
|
2007-09-20 01:32:53 +02:00
|
|
|
>>> from django.contrib.sessions.backends.db import SessionStore
|
2010-12-25 21:46:15 +01:00
|
|
|
>>> import datetime
|
2012-04-15 18:34:13 +02:00
|
|
|
>>> s = SessionStore()
|
2007-09-15 23:29:14 +02:00
|
|
|
>>> s['last_login'] = datetime.datetime(2005, 8, 20, 13, 35, 10)
|
2012-04-15 18:34:13 +02:00
|
|
|
>>> s.save()
|
|
|
|
>>> s.session_key
|
|
|
|
'2b1189a188b44ad18c35e113ac6ceead'
|
|
|
|
|
|
|
|
>>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
|
2007-09-15 23:29:14 +02:00
|
|
|
>>> s['last_login']
|
|
|
|
datetime.datetime(2005, 8, 20, 13, 35, 0)
|
|
|
|
|
2012-04-15 18:34:13 +02:00
|
|
|
In order to prevent session fixation attacks, sessions keys that don't exist
|
|
|
|
are regenerated::
|
2010-12-25 21:46:15 +01:00
|
|
|
|
|
|
|
>>> from django.contrib.sessions.backends.db import SessionStore
|
2012-04-15 18:34:13 +02:00
|
|
|
>>> s = SessionStore(session_key='no-such-session-here')
|
2010-12-25 21:46:15 +01:00
|
|
|
>>> s.save()
|
|
|
|
>>> s.session_key
|
2012-04-15 18:34:13 +02:00
|
|
|
'ff882814010ccbc3c870523934fee5a2'
|
2010-12-25 21:46:15 +01:00
|
|
|
|
2007-09-20 04:02:21 +02:00
|
|
|
If you're using the ``django.contrib.sessions.backends.db`` backend, each
|
2007-09-16 00:36:53 +02:00
|
|
|
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::
|
2005-08-17 06:00:02 +02:00
|
|
|
|
2006-05-02 03:31:56 +02:00
|
|
|
>>> from django.contrib.sessions.models import Session
|
2007-03-26 01:22:04 +02:00
|
|
|
>>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
|
2005-08-17 06:00:02 +02:00
|
|
|
>>> s.expire_date
|
2007-09-16 00:36:53 +02:00
|
|
|
datetime.datetime(2005, 8, 20, 13, 35, 12)
|
2005-08-17 06:00:02 +02:00
|
|
|
|
|
|
|
Note that you'll need to call ``get_decoded()`` to get the session dictionary.
|
|
|
|
This is necessary because the dictionary is stored in an encoded format::
|
|
|
|
|
|
|
|
>>> s.session_data
|
|
|
|
'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
|
|
|
|
>>> s.get_decoded()
|
|
|
|
{'user_id': 42}
|
|
|
|
|
2005-11-20 18:16:13 +01:00
|
|
|
When sessions are saved
|
|
|
|
=======================
|
|
|
|
|
|
|
|
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.
|
|
|
|
del request.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'
|
|
|
|
|
2007-08-12 12:24:21 +02:00
|
|
|
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
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
To change this default behavior, set the :setting:`SESSION_SAVE_EVERY_REQUEST`
|
|
|
|
setting to ``True``. When set to ``True``, Django will save the session to the
|
|
|
|
database on every single request.
|
2005-11-02 15:26:55 +01:00
|
|
|
|
2005-11-20 18:16:13 +01:00
|
|
|
Note that the session cookie is only sent when a session has been created or
|
2011-05-29 19:41:04 +02:00
|
|
|
modified. If :setting:`SESSION_SAVE_EVERY_REQUEST` is ``True``, the session
|
|
|
|
cookie will be sent on every request.
|
2005-11-20 18:16:13 +01:00
|
|
|
|
|
|
|
Similarly, the ``expires`` part of a session cookie is updated each time the
|
|
|
|
session cookie is sent.
|
|
|
|
|
2006-06-02 00:25:06 +02:00
|
|
|
Browser-length sessions vs. persistent sessions
|
|
|
|
===============================================
|
|
|
|
|
|
|
|
You can control whether the session framework uses browser-length sessions vs.
|
2011-05-20 02:51:25 +02:00
|
|
|
persistent sessions with the :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE`
|
|
|
|
setting.
|
2006-06-02 00:25:06 +02:00
|
|
|
|
2011-05-29 19:41:04 +02:00
|
|
|
By default, :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` is set to ``False``,
|
|
|
|
which means session cookies will be stored in users' browsers for as long as
|
2011-05-20 02:51:25 +02:00
|
|
|
:setting:`SESSION_COOKIE_AGE`. Use this if you don't want people to have to
|
|
|
|
log in every time they open a browser.
|
2006-06-02 00:25:06 +02:00
|
|
|
|
2011-05-29 19:41:04 +02:00
|
|
|
If :setting:`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.
|
2006-06-02 00:25:06 +02:00
|
|
|
|
2008-06-07 22:28:06 +02:00
|
|
|
This setting is a global default and can be overwritten at a per-session level
|
2011-05-20 02:51:25 +02:00
|
|
|
by explicitly calling the :meth:`~backends.base.SessionBase.set_expiry` method
|
|
|
|
of ``request.session`` as described above in `using sessions in views`_.
|
2008-06-07 22:28:06 +02:00
|
|
|
|
2006-12-30 08:30:00 +01:00
|
|
|
Clearing the session table
|
|
|
|
==========================
|
|
|
|
|
2009-05-26 07:29:28 +02:00
|
|
|
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.
|
2006-12-30 08:30:00 +01:00
|
|
|
|
|
|
|
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.
|
|
|
|
|
2009-05-26 07:29:28 +02:00
|
|
|
Django provides a sample clean-up script: ``django-admin.py cleanup``.
|
2006-12-30 08:30:00 +01:00
|
|
|
That script deletes any session in the session table whose ``expire_date`` is
|
|
|
|
in the past -- but your application may have different requirements.
|
|
|
|
|
2005-11-20 18:16:13 +01:00
|
|
|
Settings
|
|
|
|
========
|
|
|
|
|
2011-05-20 02:51:25 +02:00
|
|
|
A few :doc:`Django settings </ref/settings>` give you control over session
|
|
|
|
behavior:
|
2005-11-02 15:26:55 +01:00
|
|
|
|
2007-09-15 23:29:14 +02:00
|
|
|
SESSION_ENGINE
|
|
|
|
--------------
|
|
|
|
|
|
|
|
Default: ``django.contrib.sessions.backends.db``
|
|
|
|
|
|
|
|
Controls where Django stores session data. Valid values are:
|
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* ``'django.contrib.sessions.backends.db'``
|
|
|
|
* ``'django.contrib.sessions.backends.file'``
|
|
|
|
* ``'django.contrib.sessions.backends.cache'``
|
|
|
|
* ``'django.contrib.sessions.backends.cached_db'``
|
|
|
|
* ``'django.contrib.sessions.backends.signed_cookies'``
|
2007-09-16 00:36:53 +02:00
|
|
|
|
2007-09-15 23:29:14 +02:00
|
|
|
See `configuring the session engine`_ for more details.
|
|
|
|
|
|
|
|
SESSION_FILE_PATH
|
|
|
|
-----------------
|
|
|
|
|
|
|
|
Default: ``/tmp/``
|
|
|
|
|
|
|
|
If you're using file-based session storage, this sets the directory in
|
|
|
|
which Django will store session data.
|
|
|
|
|
2005-11-02 15:26:55 +01:00
|
|
|
SESSION_COOKIE_AGE
|
|
|
|
------------------
|
|
|
|
|
|
|
|
Default: ``1209600`` (2 weeks, in seconds)
|
|
|
|
|
|
|
|
The age of session cookies, in seconds.
|
|
|
|
|
|
|
|
SESSION_COOKIE_DOMAIN
|
|
|
|
---------------------
|
|
|
|
|
|
|
|
Default: ``None``
|
|
|
|
|
|
|
|
The domain to use for session cookies. Set this to a string such as
|
2012-06-07 11:50:20 +02:00
|
|
|
``".example.com"`` (note the leading dot!) for cross-domain cookies, or use
|
2009-05-26 07:29:28 +02:00
|
|
|
``None`` for a standard domain cookie.
|
2005-11-02 15:26:55 +01:00
|
|
|
|
2010-11-26 14:30:50 +01:00
|
|
|
SESSION_COOKIE_HTTPONLY
|
|
|
|
-----------------------
|
|
|
|
|
2011-11-21 23:03:03 +01:00
|
|
|
Default: ``True``
|
2010-11-26 14:30:50 +01:00
|
|
|
|
|
|
|
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
|
2011-09-04 23:17:30 +02:00
|
|
|
is not part of the :rfc:`2109` standard for cookies, and it isn't honored
|
2010-11-26 14:30:50 +01:00
|
|
|
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.
|
|
|
|
|
|
|
|
.. _HTTPOnly: http://www.owasp.org/index.php/HTTPOnly
|
|
|
|
|
2005-11-02 15:26:55 +01:00
|
|
|
SESSION_COOKIE_NAME
|
|
|
|
-------------------
|
|
|
|
|
2006-01-11 01:11:29 +01:00
|
|
|
Default: ``'sessionid'``
|
2005-11-02 15:26:55 +01:00
|
|
|
|
|
|
|
The name of the cookie to use for sessions. This can be whatever you want.
|
|
|
|
|
2009-09-13 02:17:35 +02:00
|
|
|
SESSION_COOKIE_PATH
|
|
|
|
-------------------
|
|
|
|
|
|
|
|
Default: ``'/'``
|
|
|
|
|
|
|
|
The path set on the session cookie. This should either match the URL path of
|
|
|
|
your Django installation or be parent of that path.
|
|
|
|
|
|
|
|
This is useful if you have multiple Django instances running under the same
|
|
|
|
hostname. They can use different cookie paths, and each instance will only see
|
|
|
|
its own session cookie.
|
|
|
|
|
2006-08-12 08:02:28 +02:00
|
|
|
SESSION_COOKIE_SECURE
|
|
|
|
---------------------
|
|
|
|
|
|
|
|
Default: ``False``
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
2006-06-02 00:25:06 +02:00
|
|
|
SESSION_EXPIRE_AT_BROWSER_CLOSE
|
|
|
|
-------------------------------
|
|
|
|
|
|
|
|
Default: ``False``
|
|
|
|
|
|
|
|
Whether to expire the session when the user closes his or her browser. See
|
|
|
|
"Browser-length sessions vs. persistent sessions" above.
|
|
|
|
|
2005-11-20 18:16:13 +01:00
|
|
|
SESSION_SAVE_EVERY_REQUEST
|
|
|
|
--------------------------
|
|
|
|
|
|
|
|
Default: ``False``
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
2007-01-24 21:08:47 +01:00
|
|
|
.. _Django settings: ../settings/
|
2005-11-02 15:26:55 +01:00
|
|
|
|
2005-08-17 06:00:02 +02:00
|
|
|
Technical details
|
|
|
|
=================
|
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* The session dictionary should accept any pickleable Python object. See
|
|
|
|
the :mod:`pickle` module for more information.
|
2005-08-17 06:00:02 +02:00
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* Session data is stored in a database table named ``django_session`` .
|
2005-08-17 06:00:02 +02:00
|
|
|
|
2011-10-14 02:12:01 +02:00
|
|
|
* Django only sends a cookie if it needs to. If you don't set any session
|
|
|
|
data, it won't send a session cookie.
|
2005-08-17 06:00:02 +02:00
|
|
|
|
2005-11-02 15:26:55 +01:00
|
|
|
Session IDs in URLs
|
|
|
|
===================
|
|
|
|
|
|
|
|
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.
|