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.
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/
67 You should probably only use cache-based sessions if you're using the
68 memcached cache backend. The local memory and simple cache backends
69 don't retain data long enough to be good choices, and it'll be faster
70 to use file or database sessions directly instead of sending everything
71 through the file 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 It implements 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')``
107 * ``setdefault()`` (**New in Django development version**)
109 It also has these methods:
111 * ``set_test_cookie()``
113 Sets a test cookie to determine whether the user's browser supports
114 cookies. Due to the way cookies work, you won't be able to test this
115 until the user's next page request. See `Setting test cookies`_ below for
118 * ``test_cookie_worked()``
120 Returns either ``True`` or ``False``, depending on whether the user's
121 browser accepted the test cookie. Due to the way cookies work, you'll
122 have to call ``set_test_cookie()`` on a previous, separate page request.
123 See `Setting test cookies`_ below for more information.
125 * ``delete_test_cookie()``
127 Deletes the test cookie. Use this to clean up after yourself.
129 * ``set_expiry(value)``
131 **New in Django development version**
133 Sets the expiration time for the session. You can pass a number of
136 * If ``value`` is an integer, the session will expire after that
137 many seconds of inactivity. For example, calling
138 ``request.session.set_expiry(300)`` would make the session expire
141 * If ``value`` is a ``datetime`` or ``timedelta`` object, the
142 session will expire at that specific date/time.
144 * If ``value`` is ``0``, the user's session cookie will expire
145 when the user's Web browser is closed.
147 * If ``value`` is ``None``, the session reverts to using the global
148 session expiry policy.
150 * ``get_expiry_age()``
152 **New in Django development version**
154 Returns the number of seconds until this session expires. For sessions
155 with no custom expiration (or those set to expire at browser close), this
156 will equal ``settings.SESSION_COOKIE_AGE``.
158 * ``get_expiry_date()``
160 **New in Django development version**
162 Returns the date this session will expire. For sessions with no custom
163 expiration (or those set to expire at browser close), this will equal the
164 date ``settings.SESSION_COOKIE_AGE`` seconds from now.
166 * ``get_expire_at_browser_close()``
168 **New in Django development version**
170 Returns either ``True`` or ``False``, depending on whether the user's
171 session cookie will expire when the user's Web browser is closed.
173 You can edit ``request.session`` at any point in your view. You can edit it
176 Session object guidelines
177 -------------------------
179 * Use normal Python strings as dictionary keys on ``request.session``. This
180 is more of a convention than a hard-and-fast rule.
182 * Session dictionary keys that begin with an underscore are reserved for
183 internal use by Django.
185 * Don't override ``request.session`` with a new object, and don't access or
186 set its attributes. Use it like a Python dictionary.
191 This simplistic view sets a ``has_commented`` variable to ``True`` after a user
192 posts a comment. It doesn't let a user post a comment more than once::
194 def post_comment(request, new_comment):
195 if request.session.get('has_commented', False):
196 return HttpResponse("You've already commented.")
197 c = comments.Comment(comment=new_comment)
199 request.session['has_commented'] = True
200 return HttpResponse('Thanks for your comment!')
202 This simplistic view logs in a "member" of the site::
205 m = Member.objects.get(username=request.POST['username'])
206 if m.password == request.POST['password']:
207 request.session['member_id'] = m.id
208 return HttpResponse("You're logged in.")
210 return HttpResponse("Your username and password didn't match.")
212 ...And this one logs a member out, according to ``login()`` above::
216 del request.session['member_id']
219 return HttpResponse("You're logged out.")
224 As a convenience, Django provides an easy way to test whether the user's
225 browser accepts cookies. Just call ``request.session.set_test_cookie()`` in a
226 view, and call ``request.session.test_cookie_worked()`` in a subsequent view --
227 not in the same view call.
229 This awkward split between ``set_test_cookie()`` and ``test_cookie_worked()``
230 is necessary due to the way cookies work. When you set a cookie, you can't
231 actually tell whether a browser accepted it until the browser's next request.
233 It's good practice to use ``delete_test_cookie()`` to clean up after yourself.
234 Do this after you've verified that the test cookie worked.
236 Here's a typical usage example::
239 if request.method == 'POST':
240 if request.session.test_cookie_worked():
241 request.session.delete_test_cookie()
242 return HttpResponse("You're logged in.")
244 return HttpResponse("Please enable cookies and try again.")
245 request.session.set_test_cookie()
246 return render_to_response('foo/login_form.html')
248 Using sessions out of views
249 ===========================
251 **New in Django development version**
253 An API is available to manipulate session data outside of a view::
255 >>> from django.contrib.sessions.backends.db import SessionStore
256 >>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
257 >>> s['last_login'] = datetime.datetime(2005, 8, 20, 13, 35, 10)
259 datetime.datetime(2005, 8, 20, 13, 35, 0)
262 If you're using the ``django.contrib.sessions.backends.db`` backend, each
263 session is just a normal Django model. The ``Session`` model is defined in
264 ``django/contrib/sessions/models.py``. Because it's a normal model, you can
265 access sessions using the normal Django database API::
267 >>> from django.contrib.sessions.models import Session
268 >>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
270 datetime.datetime(2005, 8, 20, 13, 35, 12)
272 Note that you'll need to call ``get_decoded()`` to get the session dictionary.
273 This is necessary because the dictionary is stored in an encoded format::
276 'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
280 When sessions are saved
281 =======================
283 By default, Django only saves to the session database when the session has been
284 modified -- that is if any of its dictionary values have been assigned or
287 # Session is modified.
288 request.session['foo'] = 'bar'
290 # Session is modified.
291 del request.session['foo']
293 # Session is modified.
294 request.session['foo'] = {}
296 # Gotcha: Session is NOT modified, because this alters
297 # request.session['foo'] instead of request.session.
298 request.session['foo']['bar'] = 'baz'
300 In the last case of the above example, we can tell the session object
301 explicitly that it has been modified by setting the ``modified`` attribute on
304 request.session.modified = True
306 To change this default behavior, set the ``SESSION_SAVE_EVERY_REQUEST`` setting
307 to ``True``. If ``SESSION_SAVE_EVERY_REQUEST`` is ``True``, Django will save
308 the session to the database on every single request.
310 Note that the session cookie is only sent when a session has been created or
311 modified. If ``SESSION_SAVE_EVERY_REQUEST`` is ``True``, the session cookie
312 will be sent on every request.
314 Similarly, the ``expires`` part of a session cookie is updated each time the
315 session cookie is sent.
317 Browser-length sessions vs. persistent sessions
318 ===============================================
320 You can control whether the session framework uses browser-length sessions vs.
321 persistent sessions with the ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` setting.
323 By default, ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` is set to ``False``, which
324 means session cookies will be stored in users' browsers for as long as
325 ``SESSION_COOKIE_AGE``. Use this if you don't want people to have to log in
326 every time they open a browser.
328 If ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` is set to ``True``, Django will use
329 browser-length cookies -- cookies that expire as soon as the user closes his or
330 her browser. Use this if you want people to have to log in every time they open
333 **New in Django development version**
335 This setting is a global default and can be overwritten at a per-session level
336 by explicitly calling ``request.session.set_expiry()`` as described above in
337 `using sessions in views`_.
339 Clearing the session table
340 ==========================
342 Note that session data can accumulate in the ``django_session`` database table
343 and Django does *not* provide automatic purging. Therefore, it's your job to
344 purge expired sessions on a regular basis.
346 To understand this problem, consider what happens when a user uses a session.
347 When a user logs in, Django adds a row to the ``django_session`` database
348 table. Django updates this row each time the session data changes. If the user
349 logs out manually, Django deletes the row. But if the user does *not* log out,
350 the row never gets deleted.
352 Django provides a sample clean-up script in ``django/bin/daily_cleanup.py``.
353 That script deletes any session in the session table whose ``expire_date`` is
354 in the past -- but your application may have different requirements.
359 A few `Django settings`_ give you control over session behavior:
364 **New in Django development version**
366 Default: ``django.contrib.sessions.backends.db``
368 Controls where Django stores session data. Valid values are:
370 * ``'django.contrib.sessions.backends.db'``
371 * ``'django.contrib.sessions.backends.file'``
372 * ``'django.contrib.sessions.backends.cache'``
374 See `configuring the session engine`_ for more details.
379 **New in Django development version**
383 If you're using file-based session storage, this sets the directory in
384 which Django will store session data.
389 Default: ``1209600`` (2 weeks, in seconds)
391 The age of session cookies, in seconds.
393 SESSION_COOKIE_DOMAIN
394 ---------------------
398 The domain to use for session cookies. Set this to a string such as
399 ``".lawrence.com"`` for cross-domain cookies, or use ``None`` for a standard
405 Default: ``'sessionid'``
407 The name of the cookie to use for sessions. This can be whatever you want.
409 SESSION_COOKIE_SECURE
410 ---------------------
414 Whether to use a secure cookie for the session cookie. If this is set to
415 ``True``, the cookie will be marked as "secure," which means browsers may
416 ensure that the cookie is only sent under an HTTPS connection.
418 SESSION_EXPIRE_AT_BROWSER_CLOSE
419 -------------------------------
423 Whether to expire the session when the user closes his or her browser. See
424 "Browser-length sessions vs. persistent sessions" above.
426 SESSION_SAVE_EVERY_REQUEST
427 --------------------------
431 Whether to save the session data on every request. If this is ``False``
432 (default), then the session data will only be saved if it has been modified --
433 that is, if any of its dictionary values have been assigned or deleted.
435 .. _Django settings: ../settings/
440 * The session dictionary should accept any pickleable Python object. See
441 `the pickle module`_ for more information.
443 * Session data is stored in a database table named ``django_session`` .
445 * Django only sends a cookie if it needs to. If you don't set any session
446 data, it won't send a session cookie.
448 .. _`the pickle module`: http://www.python.org/doc/current/lib/module-pickle.html
453 The Django sessions framework is entirely, and solely, cookie-based. It does
454 not fall back to putting session IDs in URLs as a last resort, as PHP does.
455 This is an intentional design decision. Not only does that behavior make URLs
456 ugly, it makes your site vulnerable to session-ID theft via the "Referer"