Fixed #8234: Corrected typo in docs/cache.txt
[django.git] / docs / sessions.txt
blobf828c76bde40e4b80d64c3e851575e776c976b87
1 ===================
2 How to use sessions
3 ===================
5 Django provides full support for anonymous sessions. The session framework lets
6 you store and retrieve arbitrary data on a per-site-visitor basis. It stores
7 data on the server side and abstracts the sending and receiving of cookies.
8 Cookies contain a session ID -- not the data itself.
10 Enabling sessions
11 =================
13 Sessions are implemented via a piece of middleware_.
15 To enable session functionality, do the following:
17     * Edit the ``MIDDLEWARE_CLASSES`` setting and make sure
18       ``MIDDLEWARE_CLASSES`` contains ``'django.contrib.sessions.middleware.SessionMiddleware'``.
19       The default ``settings.py`` created by ``django-admin.py startproject`` has
20       ``SessionMiddleware`` activated.
22     * Add ``'django.contrib.sessions'`` to your ``INSTALLED_APPS`` setting,
23       and run ``manage.py syncdb`` to install the single database table
24       that stores session data.
26       **New in development version**: this step is optional if you're not using
27       the database session backend; see `configuring the session engine`_.
29 If you don't want to use sessions, you might as well remove the
30 ``SessionMiddleware`` line from ``MIDDLEWARE_CLASSES`` and ``'django.contrib.sessions'``
31 from your ``INSTALLED_APPS``. It'll save you a small bit of overhead.
33 .. _middleware: ../middleware/
35 Configuring the session engine
36 ==============================
38 **New in development version**.
40 By default, Django stores sessions in your database (using the model
41 ``django.contrib.sessions.models.Session``). Though this is convenient, in
42 some setups it's faster to store session data elsewhere, so Django can be
43 configured to store session data on your filesystem or in your cache.
45 Using file-based sessions
46 -------------------------
48 To use file-based sessions, set the ``SESSION_ENGINE`` setting to
49 ``"django.contrib.sessions.backends.file"``.
51 You might also want to set the ``SESSION_FILE_PATH`` setting (which defaults
52 to output from ``tempfile.gettempdir()``, most likely  ``/tmp``) to control
53 where Django stores session files. Be sure to check that your Web server has
54 permissions to read and write to this location.
56 Using cache-based sessions
57 --------------------------
59 To store session data using Django's cache system, set ``SESSION_ENGINE``
60 to ``"django.contrib.sessions.backends.cache"``. You'll want to make sure
61 you've configured your cache; see the `cache documentation`_ for details.
63 .. _cache documentation: ../cache/
65 .. note::
67     You should probably only use cache-based sessions if you're using the
68     Memcached cache backend. The local-memory cache backend doesn't retain data
69     long enough to be a good choice, and it'll be faster to use file or
70     database sessions directly instead of sending everything through the file
71     or database cache backends.
73 Using sessions in views
74 =======================
76 When ``SessionMiddleware`` is activated, each ``HttpRequest`` object -- the
77 first argument to any Django view function -- will have a ``session``
78 attribute, which is a dictionary-like object. You can read it and write to it.
80 A session object has the following standard dictionary methods:
82     * ``__getitem__(key)``
84       Example: ``fav_color = request.session['fav_color']``
86     * ``__setitem__(key, value)``
88       Example: ``request.session['fav_color'] = 'blue'``
90     * ``__delitem__(key)``
92       Example: ``del request.session['fav_color']``. This raises ``KeyError``
93       if the given ``key`` isn't already in the session.
95     * ``__contains__(key)``
97       Example: ``'fav_color' in request.session``
99     * ``get(key, default=None)``
101       Example: ``fav_color = request.session.get('fav_color', 'red')``
103     * ``keys()``
105     * ``items()``
107     * ``setdefault()`` (**New in Django development version**)
109     * ``clear()`` (**New in Django development version**)
111 It also has these methods:
113     * ``flush()``
115       **New in Django development version**
117       Delete the current session data from the database and regenerate the
118       session key value that is sent back to the user in the cookie. This is
119       used if you want to ensure that the previous session data can't be
120       accessed again from the user's browser (for example, the
121       ``django.contrib.auth.logout()`` method calls it).
123     * ``set_test_cookie()``
125       Sets a test cookie to determine whether the user's browser supports
126       cookies. Due to the way cookies work, you won't be able to test this
127       until the user's next page request. See `Setting test cookies`_ below for
128       more information.
130     * ``test_cookie_worked()``
132       Returns either ``True`` or ``False``, depending on whether the user's
133       browser accepted the test cookie. Due to the way cookies work, you'll
134       have to call ``set_test_cookie()`` on a previous, separate page request.
135       See `Setting test cookies`_ below for more information.
137     * ``delete_test_cookie()``
139       Deletes the test cookie. Use this to clean up after yourself.
141     * ``set_expiry(value)``
143       **New in Django development version**
145       Sets the expiration time for the session. You can pass a number of
146       different values:
148             * If ``value`` is an integer, the session will expire after that
149               many seconds of inactivity. For example, calling
150               ``request.session.set_expiry(300)`` would make the session expire
151               in 5 minutes.
153             * If ``value`` is a ``datetime`` or ``timedelta`` object, the
154               session will expire at that specific date/time.
156             * If ``value`` is ``0``, the user's session cookie will expire
157               when the user's Web browser is closed.
159             * If ``value`` is ``None``, the session reverts to using the global
160               session expiry policy.
162     * ``get_expiry_age()``
164       **New in Django development version**
166       Returns the number of seconds until this session expires. For sessions
167       with no custom expiration (or those set to expire at browser close), this
168       will equal ``settings.SESSION_COOKIE_AGE``.
170     * ``get_expiry_date()``
172       **New in Django development version**
174       Returns the date this session will expire. For sessions with no custom
175       expiration (or those set to expire at browser close), this will equal the
176       date ``settings.SESSION_COOKIE_AGE`` seconds from now.
178     * ``get_expire_at_browser_close()``
180       **New in Django development version**
182       Returns either ``True`` or ``False``, depending on whether the user's
183       session cookie will expire when the user's Web browser is closed.
185 You can edit ``request.session`` at any point in your view. You can edit it
186 multiple times.
188 Session object guidelines
189 -------------------------
191     * Use normal Python strings as dictionary keys on ``request.session``. This
192       is more of a convention than a hard-and-fast rule.
194     * Session dictionary keys that begin with an underscore are reserved for
195       internal use by Django.
197     * Don't override ``request.session`` with a new object, and don't access or
198       set its attributes. Use it like a Python dictionary.
200 Examples
201 --------
203 This simplistic view sets a ``has_commented`` variable to ``True`` after a user
204 posts a comment. It doesn't let a user post a comment more than once::
206     def post_comment(request, new_comment):
207         if request.session.get('has_commented', False):
208             return HttpResponse("You've already commented.")
209         c = comments.Comment(comment=new_comment)
210         c.save()
211         request.session['has_commented'] = True
212         return HttpResponse('Thanks for your comment!')
214 This simplistic view logs in a "member" of the site::
216     def login(request):
217         m = Member.objects.get(username=request.POST['username'])
218         if m.password == request.POST['password']:
219             request.session['member_id'] = m.id
220             return HttpResponse("You're logged in.")
221         else:
222             return HttpResponse("Your username and password didn't match.")
224 ...And this one logs a member out, according to ``login()`` above::
226     def logout(request):
227         try:
228             del request.session['member_id']
229         except KeyError:
230             pass
231         return HttpResponse("You're logged out.")
233 The standard ``django.contrib.auth.logout()`` function actually does a bit
234 more than this to prevent inadvertent data leakage. It calls
235 ``request.session.flush()``. We are using this example as a demonstration of
236 how to work with session objects, not as a full ``logout()`` implementation.
238 Setting test cookies
239 ====================
241 As a convenience, Django provides an easy way to test whether the user's
242 browser accepts cookies. Just call ``request.session.set_test_cookie()`` in a
243 view, and call ``request.session.test_cookie_worked()`` in a subsequent view --
244 not in the same view call.
246 This awkward split between ``set_test_cookie()`` and ``test_cookie_worked()``
247 is necessary due to the way cookies work. When you set a cookie, you can't
248 actually tell whether a browser accepted it until the browser's next request.
250 It's good practice to use ``delete_test_cookie()`` to clean up after yourself.
251 Do this after you've verified that the test cookie worked.
253 Here's a typical usage example::
255     def login(request):
256         if request.method == 'POST':
257             if request.session.test_cookie_worked():
258                 request.session.delete_test_cookie()
259                 return HttpResponse("You're logged in.")
260             else:
261                 return HttpResponse("Please enable cookies and try again.")
262         request.session.set_test_cookie()
263         return render_to_response('foo/login_form.html')
265 Using sessions out of views
266 ===========================
268 **New in Django development version**
270 An API is available to manipulate session data outside of a view::
272     >>> from django.contrib.sessions.backends.db import SessionStore
273     >>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
274     >>> s['last_login'] = datetime.datetime(2005, 8, 20, 13, 35, 10)
275     >>> s['last_login']
276     datetime.datetime(2005, 8, 20, 13, 35, 0)
277     >>> s.save()
279 If you're using the ``django.contrib.sessions.backends.db`` backend, each
280 session is just a normal Django model. The ``Session`` model is defined in
281 ``django/contrib/sessions/models.py``. Because it's a normal model, you can
282 access sessions using the normal Django database API::
284     >>> from django.contrib.sessions.models import Session
285     >>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
286     >>> s.expire_date
287     datetime.datetime(2005, 8, 20, 13, 35, 12)
289 Note that you'll need to call ``get_decoded()`` to get the session dictionary.
290 This is necessary because the dictionary is stored in an encoded format::
292     >>> s.session_data
293     'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
294     >>> s.get_decoded()
295     {'user_id': 42}
297 When sessions are saved
298 =======================
300 By default, Django only saves to the session database when the session has been
301 modified -- that is if any of its dictionary values have been assigned or
302 deleted::
304     # Session is modified.
305     request.session['foo'] = 'bar'
307     # Session is modified.
308     del request.session['foo']
310     # Session is modified.
311     request.session['foo'] = {}
313     # Gotcha: Session is NOT modified, because this alters
314     # request.session['foo'] instead of request.session.
315     request.session['foo']['bar'] = 'baz'
317 In the last case of the above example, we can tell the session object
318 explicitly that it has been modified by setting the ``modified`` attribute on
319 the session object::
321     request.session.modified = True
323 To change this default behavior, set the ``SESSION_SAVE_EVERY_REQUEST`` setting
324 to ``True``. If ``SESSION_SAVE_EVERY_REQUEST`` is ``True``, Django will save
325 the session to the database on every single request.
327 Note that the session cookie is only sent when a session has been created or
328 modified. If ``SESSION_SAVE_EVERY_REQUEST`` is ``True``, the session cookie
329 will be sent on every request.
331 Similarly, the ``expires`` part of a session cookie is updated each time the
332 session cookie is sent.
334 Browser-length sessions vs. persistent sessions
335 ===============================================
337 You can control whether the session framework uses browser-length sessions vs.
338 persistent sessions with the ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` setting.
340 By default, ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` is set to ``False``, which
341 means session cookies will be stored in users' browsers for as long as
342 ``SESSION_COOKIE_AGE``. Use this if you don't want people to have to log in
343 every time they open a browser.
345 If ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` is set to ``True``, Django will use
346 browser-length cookies -- cookies that expire as soon as the user closes his or
347 her browser. Use this if you want people to have to log in every time they open
348 a browser.
350 **New in Django development version**
352 This setting is a global default and can be overwritten at a per-session level
353 by explicitly calling ``request.session.set_expiry()`` as described above in
354 `using sessions in views`_.
356 Clearing the session table
357 ==========================
359 Note that session data can accumulate in the ``django_session`` database table
360 and Django does *not* provide automatic purging. Therefore, it's your job to
361 purge expired sessions on a regular basis.
363 To understand this problem, consider what happens when a user uses a session.
364 When a user logs in, Django adds a row to the ``django_session`` database
365 table. Django updates this row each time the session data changes. If the user
366 logs out manually, Django deletes the row. But if the user does *not* log out,
367 the row never gets deleted.
369 Django provides a sample clean-up script in ``django-admin.py cleanup``.
370 That script deletes any session in the session table whose ``expire_date`` is
371 in the past -- but your application may have different requirements.
373 Settings
374 ========
376 A few `Django settings`_ give you control over session behavior:
378 SESSION_ENGINE
379 --------------
381 **New in Django development version**
383 Default: ``django.contrib.sessions.backends.db``
385 Controls where Django stores session data. Valid values are:
387     * ``'django.contrib.sessions.backends.db'``
388     * ``'django.contrib.sessions.backends.file'``
389     * ``'django.contrib.sessions.backends.cache'``
391 See `configuring the session engine`_ for more details.
393 SESSION_FILE_PATH
394 -----------------
396 **New in Django development version**
398 Default: ``/tmp/``
400 If you're using file-based session storage, this sets the directory in
401 which Django will store session data.
403 SESSION_COOKIE_AGE
404 ------------------
406 Default: ``1209600`` (2 weeks, in seconds)
408 The age of session cookies, in seconds.
410 SESSION_COOKIE_DOMAIN
411 ---------------------
413 Default: ``None``
415 The domain to use for session cookies. Set this to a string such as
416 ``".lawrence.com"`` for cross-domain cookies, or use ``None`` for a standard
417 domain cookie.
419 SESSION_COOKIE_NAME
420 -------------------
422 Default: ``'sessionid'``
424 The name of the cookie to use for sessions. This can be whatever you want.
426 SESSION_COOKIE_SECURE
427 ---------------------
429 Default: ``False``
431 Whether to use a secure cookie for the session cookie. If this is set to
432 ``True``, the cookie will be marked as "secure," which means browsers may
433 ensure that the cookie is only sent under an HTTPS connection.
435 SESSION_EXPIRE_AT_BROWSER_CLOSE
436 -------------------------------
438 Default: ``False``
440 Whether to expire the session when the user closes his or her browser. See
441 "Browser-length sessions vs. persistent sessions" above.
443 SESSION_SAVE_EVERY_REQUEST
444 --------------------------
446 Default: ``False``
448 Whether to save the session data on every request. If this is ``False``
449 (default), then the session data will only be saved if it has been modified --
450 that is, if any of its dictionary values have been assigned or deleted.
452 .. _Django settings: ../settings/
454 Technical details
455 =================
457     * The session dictionary should accept any pickleable Python object. See
458       `the pickle module`_ for more information.
460     * Session data is stored in a database table named ``django_session`` .
462     * Django only sends a cookie if it needs to. If you don't set any session
463       data, it won't send a session cookie.
465 .. _`the pickle module`: http://www.python.org/doc/current/lib/module-pickle.html
467 Session IDs in URLs
468 ===================
470 The Django sessions framework is entirely, and solely, cookie-based. It does
471 not fall back to putting session IDs in URLs as a last resort, as PHP does.
472 This is an intentional design decision. Not only does that behavior make URLs
473 ugly, it makes your site vulnerable to session-ID theft via the "Referer"
474 header.