Tidy up the sessions documentation creating links for session methods and crosslinking settings

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16245 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Chris Beaven 2011-05-20 00:51:25 +00:00
parent 9f02d80b58
commit 26156794f1
1 changed files with 65 additions and 55 deletions

View File

@ -17,14 +17,15 @@ Sessions are implemented via a piece of :doc:`middleware </ref/middleware>`.
To enable session functionality, do the following: To enable session functionality, do the following:
* Edit the ``MIDDLEWARE_CLASSES`` setting and make sure * Edit the :setting:`MIDDLEWARE_CLASSES` setting and make sure
``MIDDLEWARE_CLASSES`` contains ``'django.contrib.sessions.middleware.SessionMiddleware'``. it contains ``'django.contrib.sessions.middleware.SessionMiddleware'``.
The default ``settings.py`` created by ``django-admin.py startproject`` has The default ``settings.py`` created by ``django-admin.py startproject``
``SessionMiddleware`` activated. has ``SessionMiddleware`` activated.
If you don't want to use sessions, you might as well remove the If you don't want to use sessions, you might as well remove the
``SessionMiddleware`` line from ``MIDDLEWARE_CLASSES`` and ``'django.contrib.sessions'`` ``SessionMiddleware`` line from ``MIDDLEWARE_CLASSES`` and
from your ``INSTALLED_APPS``. It'll save you a small bit of overhead. ``'django.contrib.sessions'`` from your :setting:`INSTALLED_APPS`.
It'll save you a small bit of overhead.
Configuring the session engine Configuring the session engine
============================== ==============================
@ -86,56 +87,62 @@ configuration instructions for the `using database-backed sessions`_.
Using file-based sessions Using file-based sessions
------------------------- -------------------------
To use file-based sessions, set the ``SESSION_ENGINE`` setting to To use file-based sessions, set the :setting:`SESSION_ENGINE` setting to
``"django.contrib.sessions.backends.file"``. ``"django.contrib.sessions.backends.file"``.
You might also want to set the ``SESSION_FILE_PATH`` setting (which defaults You might also want to set the :setting:`SESSION_FILE_PATH` setting (which
to output from ``tempfile.gettempdir()``, most likely ``/tmp``) to control defaults to output from ``tempfile.gettempdir()``, most likely ``/tmp``) to
where Django stores session files. Be sure to check that your Web server has control where Django stores session files. Be sure to check that your Web
permissions to read and write to this location. server has permissions to read and write to this location.
Using sessions in views Using sessions in views
======================= =======================
When ``SessionMiddleware`` is activated, each ``HttpRequest`` object -- the When ``SessionMiddleware`` is activated, each :class:`~django.http.HttpRequest`
first argument to any Django view function -- will have a ``session`` object -- the first argument to any Django view function -- will have a
attribute, which is a dictionary-like object. You can read it and write to it. ``session`` attribute, which is a dictionary-like object.
A session object has the following standard dictionary methods: You can read it and write to ``request.session`` at any point in your view.
You can edit it multiple times.
* ``__getitem__(key)`` .. class:: backends.base.SessionBase
This is the base class for all session objects. It has the following
standard dictionary methods:
.. method:: __getitem__(key)
Example: ``fav_color = request.session['fav_color']`` Example: ``fav_color = request.session['fav_color']``
* ``__setitem__(key, value)`` .. method:: __setitem__(key, value)
Example: ``request.session['fav_color'] = 'blue'`` Example: ``request.session['fav_color'] = 'blue'``
* ``__delitem__(key)`` .. method:: __delitem__(key)
Example: ``del request.session['fav_color']``. This raises ``KeyError`` Example: ``del request.session['fav_color']``. This raises ``KeyError``
if the given ``key`` isn't already in the session. if the given ``key`` isn't already in the session.
* ``__contains__(key)`` .. method:: __contains__(key)
Example: ``'fav_color' in request.session`` Example: ``'fav_color' in request.session``
* ``get(key, default=None)`` .. method:: get(key, default=None)
Example: ``fav_color = request.session.get('fav_color', 'red')`` Example: ``fav_color = request.session.get('fav_color', 'red')``
* ``keys()`` .. method:: keys
* ``items()`` .. method:: items
* ``setdefault()`` .. method:: setdefault
* ``clear()`` .. method:: clear
It also has these methods: It also has these methods:
* ``flush()`` .. method:: flush
Delete the current session data from the session and regenerate the 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 session key value that is sent back to the user in the cookie. This is
@ -143,25 +150,25 @@ It also has these methods:
accessed again from the user's browser (for example, the accessed again from the user's browser (for example, the
:func:`django.contrib.auth.logout()` function calls it). :func:`django.contrib.auth.logout()` function calls it).
* ``set_test_cookie()`` .. method:: set_test_cookie
Sets a test cookie to determine whether the user's browser supports 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 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 until the user's next page request. See `Setting test cookies`_ below for
more information. more information.
* ``test_cookie_worked()`` .. method:: test_cookie_worked
Returns either ``True`` or ``False``, depending on whether the user's Returns either ``True`` or ``False``, depending on whether the user's
browser accepted the test cookie. Due to the way cookies work, you'll 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. have to call ``set_test_cookie()`` on a previous, separate page request.
See `Setting test cookies`_ below for more information. See `Setting test cookies`_ below for more information.
* ``delete_test_cookie()`` .. method:: delete_test_cookie
Deletes the test cookie. Use this to clean up after yourself. Deletes the test cookie. Use this to clean up after yourself.
* ``set_expiry(value)`` .. method:: set_expiry(value)
Sets the expiration time for the session. You can pass a number of Sets the expiration time for the session. You can pass a number of
different values: different values:
@ -184,26 +191,23 @@ It also has these methods:
purposes. Session expiration is computed from the last time the purposes. Session expiration is computed from the last time the
session was *modified*. session was *modified*.
* ``get_expiry_age()`` .. method:: get_expiry_age
Returns the number of seconds until this session expires. For sessions Returns the number of seconds until this session expires. For sessions
with no custom expiration (or those set to expire at browser close), this with no custom expiration (or those set to expire at browser close), this
will equal ``settings.SESSION_COOKIE_AGE``. will equal :setting:`SESSION_COOKIE_AGE`.
* ``get_expiry_date()`` .. method:: get_expiry_date
Returns the date this session will expire. For sessions with no custom 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 expiration (or those set to expire at browser close), this will equal the
date ``settings.SESSION_COOKIE_AGE`` seconds from now. date :setting:`SESSION_COOKIE_AGE` seconds from now.
* ``get_expire_at_browser_close()`` .. method:: get_expire_at_browser_close
Returns either ``True`` or ``False``, depending on whether the user's Returns either ``True`` or ``False``, depending on whether the user's
session cookie will expire when the user's Web browser is closed. session cookie will expire when the user's Web browser is closed.
You can edit ``request.session`` at any point in your view. You can edit it
multiple times.
Session object guidelines Session object guidelines
------------------------- -------------------------
@ -249,25 +253,29 @@ This simplistic view logs in a "member" of the site::
pass pass
return HttpResponse("You're logged out.") return HttpResponse("You're logged out.")
The standard ``django.contrib.auth.logout()`` function actually does a bit The standard :meth:`django.contrib.auth.logout` function actually does a bit
more than this to prevent inadvertent data leakage. It calls more than this to prevent inadvertent data leakage. It calls the
``request.session.flush()``. We are using this example as a demonstration of :meth:`~backends.base.SessionBase.flush` method of ``request.session``.
how to work with session objects, not as a full ``logout()`` implementation. We are using this example as a demonstration of how to work with session
objects, not as a full ``logout()`` implementation.
Setting test cookies Setting test cookies
==================== ====================
As a convenience, Django provides an easy way to test whether the user's As a convenience, Django provides an easy way to test whether the user's
browser accepts cookies. Just call ``request.session.set_test_cookie()`` in a browser accepts cookies. Just call the
view, and call ``request.session.test_cookie_worked()`` in a subsequent view -- :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 --
not in the same view call. not in the same view call.
This awkward split between ``set_test_cookie()`` and ``test_cookie_worked()`` 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 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. 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. It's good practice to use
Do this after you've verified that the test cookie worked. :meth:`~backends.base.SessionBase.delete_test_cookie()` to clean up after
yourself. Do this after you've verified that the test cookie worked.
Here's a typical usage example:: Here's a typical usage example::
@ -346,9 +354,9 @@ the session object::
request.session.modified = True request.session.modified = True
To change this default behavior, set the ``SESSION_SAVE_EVERY_REQUEST`` setting To change this default behavior, set the :setting:`SESSION_SAVE_EVERY_REQUEST`
to ``True``. If ``SESSION_SAVE_EVERY_REQUEST`` is ``True``, Django will save setting to ``True``. When set to ``True``, Django will save the session to the
the session to the database on every single request. database on every single request.
Note that the session cookie is only sent when a session has been created or 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 modified. If ``SESSION_SAVE_EVERY_REQUEST`` is ``True``, the session cookie
@ -361,12 +369,13 @@ Browser-length sessions vs. persistent sessions
=============================================== ===============================================
You can control whether the session framework uses browser-length sessions vs. You can control whether the session framework uses browser-length sessions vs.
persistent sessions with the ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` setting. persistent sessions with the :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE`
setting.
By default, ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` is set to ``False``, which By default, ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` is set to ``False``, which
means session cookies will be stored in users' browsers for as long as means session cookies will be stored in users' browsers for as long as
``SESSION_COOKIE_AGE``. Use this if you don't want people to have to log in :setting:`SESSION_COOKIE_AGE`. Use this if you don't want people to have to
every time they open a browser. log in every time they open a browser.
If ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` is set to ``True``, Django will use 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 browser-length cookies -- cookies that expire as soon as the user closes his or
@ -374,8 +383,8 @@ her browser. Use this if you want people to have to log in every time they open
a browser. a browser.
This setting is a global default and can be overwritten at a per-session level This setting is a global default and can be overwritten at a per-session level
by explicitly calling ``request.session.set_expiry()`` as described above in by explicitly calling the :meth:`~backends.base.SessionBase.set_expiry` method
`using sessions in views`_. of ``request.session`` as described above in `using sessions in views`_.
Clearing the session table Clearing the session table
========================== ==========================
@ -397,7 +406,8 @@ in the past -- but your application may have different requirements.
Settings Settings
======== ========
A few :doc:`Django settings </ref/settings>` give you control over session behavior: A few :doc:`Django settings </ref/settings>` give you control over session
behavior:
SESSION_ENGINE SESSION_ENGINE
-------------- --------------