Debian Codegraph @

docs/topics/http/sessions.txt

raw
1 ===================
2 How to use sessions
3 ===================
4
5 .. module:: django.contrib.sessions
6 :synopsis: Provides session management for Django projects.
7
8 Django provides full support for anonymous sessions. The session framework
9 lets you store and retrieve arbitrary data on a per-site-visitor basis. It
10 stores data on the server side and abstracts the sending and receiving of
11 cookies. Cookies contain a session ID -- not the data itself (unless you're
12 using the :ref:`cookie based backend<cookie-session-backend>`).
13
14 Enabling sessions
15 =================
16
17 Sessions are implemented via a piece of :doc:`middleware </ref/middleware>`.
18
19 To enable session functionality, do the following:
20
21 * Edit the :setting:`MIDDLEWARE` setting and make sure it contains
22 ``'django.contrib.sessions.middleware.SessionMiddleware'``. The default
23 ``settings.py`` created by ``django-admin startproject`` has
24 ``SessionMiddleware`` activated.
25
26 If you don't want to use sessions, you might as well remove the
27 ``SessionMiddleware`` line from :setting:`MIDDLEWARE` and
28 ``'django.contrib.sessions'`` from your :setting:`INSTALLED_APPS`.
29 It'll save you a small bit of overhead.
30
31 .. _configuring-sessions:
32
33 Configuring the session engine
34 ==============================
35
36 By default, Django stores sessions in your database (using the model
37 ``django.contrib.sessions.models.Session``). Though this is convenient, in
38 some setups it's faster to store session data elsewhere, so Django can be
39 configured to store session data on your filesystem or in your cache.
40
41 Using database-backed sessions
42 ------------------------------
43
44 If you want to use a database-backed session, you need to add
45 ``'django.contrib.sessions'`` to your :setting:`INSTALLED_APPS` setting.
46
47 Once you have configured your installation, run ``manage.py migrate``
48 to install the single database table that stores session data.
49
50 .. _cached-sessions-backend:
51
52 Using cached sessions
53 ---------------------
54
55 For better performance, you may want to use a cache-based session backend.
56
57 To store session data using Django's cache system, you'll first need to make
58 sure you've configured your cache; see the :doc:`cache documentation
59 </topics/cache>` for details.
60
61 .. warning::
62
63 You should only use cache-based sessions if you're using the Memcached or
64 Redis cache backend. The local-memory cache backend doesn't retain data
65 long enough to be a good choice, and it'll be faster to use file or
66 database sessions directly instead of sending everything through the file
67 or database cache backends. Additionally, the local-memory cache backend is
68 NOT multi-process safe, therefore probably not a good choice for production
69 environments.
70
71 If you have multiple caches defined in :setting:`CACHES`, Django will use the
72 default cache. To use another cache, set :setting:`SESSION_CACHE_ALIAS` to the
73 name of that cache.
74
75 Once your cache is configured, you have to choose between a database-backed
76 cache or a non-persistent cache.
77
78 The cached database backend (``cached_db``) uses a write-through cache --
79 session writes are applied to both the database and cache, in that order. If
80 writing to the cache fails, the exception is handled and logged via the
81 :ref:`sessions logger <django-contrib-sessions-logger>`, to avoid failing an
82 otherwise successful write operation.
83
84 .. versionchanged:: 5.1
85
86 Handling and logging of exceptions when writing to the cache was added.
87
88 Session reads use the cache, or the database if the data has been evicted from
89 the cache. To use this backend, set :setting:`SESSION_ENGINE` to
90 ``"django.contrib.sessions.backends.cached_db"``, and follow the configuration
91 instructions for the `using database-backed sessions`_.
92
93 The cache backend (``cache``) stores session data only in your cache. This is
94 faster because it avoids database persistence, but you will have to consider
95 what happens when cache data is evicted. Eviction can occur if the cache fills
96 up or the cache server is restarted, and it will mean session data is lost,
97 including logging out users. To use this backend, set :setting:`SESSION_ENGINE`
98 to ``"django.contrib.sessions.backends.cache"``.
99
100 The cache backend can be made persistent by using a persistent cache, such as
101 Redis with appropriate configuration. But unless your cache is definitely
102 configured for sufficient persistence, opt for the cached database backend.
103 This avoids edge cases caused by unreliable data storage in production.
104
105 Using file-based sessions
106 -------------------------
107
108 To use file-based sessions, set the :setting:`SESSION_ENGINE` setting to
109 ``"django.contrib.sessions.backends.file"``.
110
111 You might also want to set the :setting:`SESSION_FILE_PATH` setting (which
112 defaults to output from ``tempfile.gettempdir()``, most likely ``/tmp``) to
113 control where Django stores session files. Be sure to check that your web
114 server has permissions to read and write to this location.
115
116 .. _cookie-session-backend:
117
118 Using cookie-based sessions
119 ---------------------------
120
121 To use cookies-based sessions, set the :setting:`SESSION_ENGINE` setting to
122 ``"django.contrib.sessions.backends.signed_cookies"``. The session data will be
123 stored using Django's tools for :doc:`cryptographic signing </topics/signing>`
124 and the :setting:`SECRET_KEY` setting.
125
126 .. note::
127
128 It's recommended to leave the :setting:`SESSION_COOKIE_HTTPONLY` setting
129 on ``True`` to prevent access to the stored data from JavaScript.
130
131 .. warning::
132
133 **The session data is signed but not encrypted**
134
135 When using the cookies backend the session data can be read by the client.
136
137 A MAC (Message Authentication Code) is used to protect the data against
138 changes by the client, so that the session data will be invalidated when being
139 tampered with. The same invalidation happens if the client storing the
140 cookie (e.g. your user's browser) can't store all of the session cookie and
141 drops data. Even though Django compresses the data, it's still entirely
142 possible to exceed the :rfc:`common limit of 4096 bytes <2965#section-5.3>`
143 per cookie.
144
145 **No freshness guarantee**
146
147 Note also that while the MAC can guarantee the authenticity of the data
148 (that it was generated by your site, and not someone else), and the
149 integrity of the data (that it is all there and correct), it cannot
150 guarantee freshness i.e. that you are being sent back the last thing you
151 sent to the client. This means that for some uses of session data, the
152 cookie backend might open you up to `replay attacks`_. Unlike other session
153 backends which keep a server-side record of each session and invalidate it
154 when a user logs out, cookie-based sessions are not invalidated when a user
155 logs out. Thus if an attacker steals a user's cookie, they can use that
156 cookie to login as that user even if the user logs out. Cookies will only
157 be detected as 'stale' if they are older than your
158 :setting:`SESSION_COOKIE_AGE`.
159
160 **Performance**
161
162 Finally, the size of a cookie can have an impact on the speed of your site.
163
164 .. _`replay attacks`: https://en.wikipedia.org/wiki/Replay_attack
165
166 Using sessions in views
167 =======================
168
169 When ``SessionMiddleware`` is activated, each :class:`~django.http.HttpRequest`
170 object -- the first argument to any Django view function -- will have a
171 ``session`` attribute, which is a dictionary-like object.
172
173 You can read it and write to ``request.session`` at any point in your view.
174 You can edit it multiple times.
175
176 .. class:: backends.base.SessionBase
177
178 This is the base class for all session objects. It has the following
179 standard dictionary methods:
180
181 .. method:: __getitem__(key)
182
183 Example: ``fav_color = request.session['fav_color']``
184
185 .. method:: __setitem__(key, value)
186
187 Example: ``request.session['fav_color'] = 'blue'``
188
189 .. method:: __delitem__(key)
190
191 Example: ``del request.session['fav_color']``. This raises ``KeyError``
192 if the given ``key`` isn't already in the session.
193
194 .. method:: __contains__(key)
195
196 Example: ``'fav_color' in request.session``
197
198 .. method:: get(key, default=None)
199 .. method:: aget(key, default=None)
200
201 *Asynchronous version*: ``aget()``
202
203 Example: ``fav_color = request.session.get('fav_color', 'red')``
204
205 .. versionchanged:: 5.1
206
207 ``aget()`` function was added.
208
209 .. method:: aset(key, value)
210
211 .. versionadded:: 5.1
212
213 Example: ``await request.session.aset('fav_color', 'red')``
214
215 .. method:: update(dict)
216 .. method:: aupdate(dict)
217
218 *Asynchronous version*: ``aupdate()``
219
220 Example: ``request.session.update({'fav_color': 'red'})``
221
222 .. versionchanged:: 5.1
223
224 ``aupdate()`` function was added.
225
226 .. method:: pop(key, default=__not_given)
227 .. method:: apop(key, default=__not_given)
228
229 *Asynchronous version*: ``apop()``
230
231 Example: ``fav_color = request.session.pop('fav_color', 'blue')``
232
233 .. versionchanged:: 5.1
234
235 ``apop()`` function was added.
236
237 .. method:: keys()
238 .. method:: akeys()
239
240 *Asynchronous version*: ``akeys()``
241
242 .. versionchanged:: 5.1
243
244 ``akeys()`` function was added.
245
246 .. method:: values()
247 .. method:: avalues()
248
249 *Asynchronous version*: ``avalues()``
250
251 .. versionchanged:: 5.1
252
253 ``avalues()`` function was added.
254
255 .. method:: has_key(key)
256 .. method:: ahas_key(key)
257
258 *Asynchronous version*: ``ahas_key()``
259
260 .. versionchanged:: 5.1
261
262 ``ahas_key()`` function was added.
263
264 .. method:: items()
265 .. method:: aitems()
266
267 *Asynchronous version*: ``aitems()``
268
269 .. versionchanged:: 5.1
270
271 ``aitems()`` function was added.
272
273 .. method:: setdefault()
274 .. method:: asetdefault()
275
276 *Asynchronous version*: ``asetdefault()``
277
278 .. versionchanged:: 5.1
279
280 ``asetdefault()`` function was added.
281
282 .. method:: clear()
283
284 It also has these methods:
285
286 .. method:: flush()
287 .. method:: aflush()
288
289 *Asynchronous version*: ``aflush()``
290
291 Deletes the current session data from the session and deletes the session
292 cookie. This is used if you want to ensure that the previous session data
293 can't be accessed again from the user's browser (for example, the
294 :func:`django.contrib.auth.logout()` function calls it).
295
296 .. versionchanged:: 5.1
297
298 ``aflush()`` function was added.
299
300 .. method:: set_test_cookie()
301 .. method:: aset_test_cookie()
302
303 *Asynchronous version*: ``aset_test_cookie()``
304
305 Sets a test cookie to determine whether the user's browser supports
306 cookies. Due to the way cookies work, you won't be able to test this
307 until the user's next page request. See `Setting test cookies`_ below for
308 more information.
309
310 .. versionchanged:: 5.1
311
312 ``aset_test_cookie()`` function was added.
313
314 .. method:: test_cookie_worked()
315 .. method:: atest_cookie_worked()
316
317 *Asynchronous version*: ``atest_cookie_worked()``
318
319 Returns either ``True`` or ``False``, depending on whether the user's
320 browser accepted the test cookie. Due to the way cookies work, you'll
321 have to call ``set_test_cookie()`` or ``aset_test_cookie()`` on a
322 previous, separate page request.
323 See `Setting test cookies`_ below for more information.
324
325 .. versionchanged:: 5.1
326
327 ``atest_cookie_worked()`` function was added.
328
329 .. method:: delete_test_cookie()
330 .. method:: adelete_test_cookie()
331
332 *Asynchronous version*: ``adelete_test_cookie()``
333
334 Deletes the test cookie. Use this to clean up after yourself.
335
336 .. versionchanged:: 5.1
337
338 ``adelete_test_cookie()`` function was added.
339
340 .. method:: get_session_cookie_age()
341
342 Returns the value of the setting :setting:`SESSION_COOKIE_AGE`. This can
343 be overridden in a custom session backend.
344
345 .. method:: set_expiry(value)
346 .. method:: aset_expiry(value)
347
348 *Asynchronous version*: ``aset_expiry()``
349
350 Sets the expiration time for the session. You can pass a number of
351 different values:
352
353 * If ``value`` is an integer, the session will expire after that
354 many seconds of inactivity. For example, calling
355 ``request.session.set_expiry(300)`` would make the session expire
356 in 5 minutes.
357
358 * If ``value`` is a ``datetime`` or ``timedelta`` object, the session
359 will expire at that specific date/time.
360
361 * If ``value`` is ``0``, the user's session cookie will expire
362 when the user's web browser is closed.
363
364 * If ``value`` is ``None``, the session reverts to using the global
365 session expiry policy.
366
367 Reading a session is not considered activity for expiration
368 purposes. Session expiration is computed from the last time the
369 session was *modified*.
370
371 .. versionchanged:: 5.1
372
373 ``aset_expiry()`` function was added.
374
375 .. method:: get_expiry_age()
376 .. method:: aget_expiry_age()
377
378 *Asynchronous version*: ``aget_expiry_age()``
379
380 Returns the number of seconds until this session expires. For sessions
381 with no custom expiration (or those set to expire at browser close), this
382 will equal :setting:`SESSION_COOKIE_AGE`.
383
384 This function accepts two optional keyword arguments:
385
386 - ``modification``: last modification of the session, as a
387 :class:`~datetime.datetime` object. Defaults to the current time.
388 - ``expiry``: expiry information for the session, as a
389 :class:`~datetime.datetime` object, an :class:`int` (in seconds), or
390 ``None``. Defaults to the value stored in the session by
391 :meth:`set_expiry`/:meth:`aset_expiry`, if there is one, or ``None``.
392
393 .. note::
394
395 This method is used by session backends to determine the session expiry
396 age in seconds when saving the session. It is not really intended for
397 usage outside of that context.
398
399 In particular, while it is **possible** to determine the remaining
400 lifetime of a session **just when** you have the correct
401 ``modification`` value **and** the ``expiry`` is set as a ``datetime``
402 object, where you do have the ``modification`` value, it is more
403 straight-forward to calculate the expiry by-hand::
404
405 expires_at = modification + timedelta(seconds=settings.SESSION_COOKIE_AGE)
406
407 .. versionchanged:: 5.1
408
409 ``aget_expiry_age()`` function was added.
410
411 .. method:: get_expiry_date()
412 .. method:: aget_expiry_date()
413
414 *Asynchronous version*: ``aget_expiry_date()``
415
416 Returns the date this session will expire. For sessions with no custom
417 expiration (or those set to expire at browser close), this will equal the
418 date :setting:`SESSION_COOKIE_AGE` seconds from now.
419
420 This function accepts the same keyword arguments as
421 :meth:`get_expiry_age`, and similar notes on usage apply.
422
423 .. versionchanged:: 5.1
424
425 ``aget_expiry_date()`` function was added.
426
427 .. method:: get_expire_at_browser_close()
428 .. method:: aget_expire_at_browser_close()
429
430 *Asynchronous version*: ``aget_expire_at_browser_close()``
431
432 Returns either ``True`` or ``False``, depending on whether the user's
433 session cookie will expire when the user's web browser is closed.
434
435 .. versionchanged:: 5.1
436
437 ``aget_expire_at_browser_close()`` function was added.
438
439 .. method:: clear_expired()
440 .. method:: aclear_expired()
441
442 *Asynchronous version*: ``aclear_expired()``
443
444 Removes expired sessions from the session store. This class method is
445 called by :djadmin:`clearsessions`.
446
447 .. versionchanged:: 5.1
448
449 ``aclear_expired()`` function was added.
450
451 .. method:: cycle_key()
452 .. method:: acycle_key()
453
454 *Asynchronous version*: ``acycle_key()``
455
456 Creates a new session key while retaining the current session data.
457 :func:`django.contrib.auth.login()` calls this method to mitigate against
458 session fixation.
459
460 .. versionchanged:: 5.1
461
462 ``acycle_key()`` function was added.
463
464 .. _session_serialization:
465
466 Session serialization
467 ---------------------
468
469 By default, Django serializes session data using JSON. You can use the
470 :setting:`SESSION_SERIALIZER` setting to customize the session serialization
471 format. Even with the caveats described in :ref:`custom-serializers`, we highly
472 recommend sticking with JSON serialization *especially if you are using the
473 cookie backend*.
474
475 For example, here's an attack scenario if you use :mod:`pickle` to serialize
476 session data. If you're using the :ref:`signed cookie session backend
477 <cookie-session-backend>` and :setting:`SECRET_KEY` (or any key of
478 :setting:`SECRET_KEY_FALLBACKS`) is known by an attacker (there isn't an
479 inherent vulnerability in Django that would cause it to leak), the attacker
480 could insert a string into their session which, when unpickled, executes
481 arbitrary code on the server. The technique for doing so is simple and easily
482 available on the internet. Although the cookie session storage signs the
483 cookie-stored data to prevent tampering, a :setting:`SECRET_KEY` leak
484 immediately escalates to a remote code execution vulnerability.
485
486 Bundled serializers
487 ~~~~~~~~~~~~~~~~~~~
488
489 .. class:: serializers.JSONSerializer
490
491 A wrapper around the JSON serializer from :mod:`django.core.signing`. Can
492 only serialize basic data types.
493
494 In addition, as JSON supports only string keys, note that using non-string
495 keys in ``request.session`` won't work as expected:
496
497 .. code-block:: pycon
498
499 >>> # initial assignment
500 >>> request.session[0] = "bar"
501 >>> # subsequent requests following serialization & deserialization
502 >>> # of session data
503 >>> request.session[0] # KeyError
504 >>> request.session["0"]
505 'bar'
506
507 Similarly, data that can't be encoded in JSON, such as non-UTF8 bytes like
508 ``'\xd9'`` (which raises :exc:`UnicodeDecodeError`), can't be stored.
509
510 See the :ref:`custom-serializers` section for more details on limitations
511 of JSON serialization.
512
513 .. _custom-serializers:
514
515 Write your own serializer
516 ~~~~~~~~~~~~~~~~~~~~~~~~~
517
518 Note that the :class:`~django.contrib.sessions.serializers.JSONSerializer`
519 cannot handle arbitrary Python data types. As is often the case, there is a
520 trade-off between convenience and security. If you wish to store more advanced
521 data types including ``datetime`` and ``Decimal`` in JSON backed sessions, you
522 will need to write a custom serializer (or convert such values to a JSON
523 serializable object before storing them in ``request.session``). While
524 serializing these values is often straightforward
525 (:class:`~django.core.serializers.json.DjangoJSONEncoder` may be helpful),
526 writing a decoder that can reliably get back the same thing that you put in is
527 more fragile. For example, you run the risk of returning a ``datetime`` that
528 was actually a string that just happened to be in the same format chosen for
529 ``datetime``\s).
530
531 Your serializer class must implement two methods,
532 ``dumps(self, obj)`` and ``loads(self, data)``, to serialize and deserialize
533 the dictionary of session data, respectively.
534
535 Session object guidelines
536 -------------------------
537
538 * Use normal Python strings as dictionary keys on ``request.session``. This
539 is more of a convention than a hard-and-fast rule.
540
541 * Session dictionary keys that begin with an underscore are reserved for
542 internal use by Django.
543
544 * Don't override ``request.session`` with a new object, and don't access or
545 set its attributes. Use it like a Python dictionary.
546
547 Examples
548 --------
549
550 This simplistic view sets a ``has_commented`` variable to ``True`` after a user
551 posts a comment. It doesn't let a user post a comment more than once::
552
553 def post_comment(request, new_comment):
554 if request.session.get("has_commented", False):
555 return HttpResponse("You've already commented.")
556 c = comments.Comment(comment=new_comment)
557 c.save()
558 request.session["has_commented"] = True
559 return HttpResponse("Thanks for your comment!")
560
561 This simplistic view logs in a "member" of the site::
562
563 def login(request):
564 m = Member.objects.get(username=request.POST["username"])
565 if m.check_password(request.POST["password"]):
566 request.session["member_id"] = m.id
567 return HttpResponse("You're logged in.")
568 else:
569 return HttpResponse("Your username and password didn't match.")
570
571 ...And this one logs a member out, according to ``login()`` above::
572
573 def logout(request):
574 try:
575 del request.session["member_id"]
576 except KeyError:
577 pass
578 return HttpResponse("You're logged out.")
579
580 The standard :meth:`django.contrib.auth.logout` function actually does a bit
581 more than this to prevent inadvertent data leakage. It calls the
582 :meth:`~backends.base.SessionBase.flush` method of ``request.session``.
583 We are using this example as a demonstration of how to work with session
584 objects, not as a full ``logout()`` implementation.
585
586 Setting test cookies
587 ====================
588
589 As a convenience, Django provides a way to test whether the user's browser
590 accepts cookies. Call the :meth:`~backends.base.SessionBase.set_test_cookie`
591 method of ``request.session`` in a view, and call
592 :meth:`~backends.base.SessionBase.test_cookie_worked` in a subsequent view --
593 not in the same view call.
594
595 This awkward split between ``set_test_cookie()`` and ``test_cookie_worked()``
596 is necessary due to the way cookies work. When you set a cookie, you can't
597 actually tell whether a browser accepted it until the browser's next request.
598
599 It's good practice to use
600 :meth:`~backends.base.SessionBase.delete_test_cookie()` to clean up after
601 yourself. Do this after you've verified that the test cookie worked.
602
603 Here's a typical usage example::
604
605 from django.http import HttpResponse
606 from django.shortcuts import render
607
608
609 def login(request):
610 if request.method == "POST":
611 if request.session.test_cookie_worked():
612 request.session.delete_test_cookie()
613 return HttpResponse("You're logged in.")
614 else:
615 return HttpResponse("Please enable cookies and try again.")
616 request.session.set_test_cookie()
617 return render(request, "foo/login_form.html")
618
619 .. versionchanged:: 5.1
620
621 Support for setting test cookies in asynchronous view functions was added.
622
623 Using sessions out of views
624 ===========================
625
626 .. note::
627
628 The examples in this section import the ``SessionStore`` object directly
629 from the ``django.contrib.sessions.backends.db`` backend. In your own code,
630 you should consider importing ``SessionStore`` from the session engine
631 designated by :setting:`SESSION_ENGINE`, as below:
632
633 .. code-block:: pycon
634
635 >>> from importlib import import_module
636 >>> from django.conf import settings
637 >>> SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
638
639 An API is available to manipulate session data outside of a view:
640
641 .. code-block:: pycon
642
643 >>> from django.contrib.sessions.backends.db import SessionStore
644 >>> s = SessionStore()
645 >>> # stored as seconds since epoch since datetimes are not serializable in JSON.
646 >>> s["last_login"] = 1376587691
647 >>> s.create()
648 >>> s.session_key
649 '2b1189a188b44ad18c35e113ac6ceead'
650 >>> s = SessionStore(session_key="2b1189a188b44ad18c35e113ac6ceead")
651 >>> s["last_login"]
652 1376587691
653
654 ``SessionStore.create()`` is designed to create a new session (i.e. one not
655 loaded from the session store and with ``session_key=None``). ``save()`` is
656 designed to save an existing session (i.e. one loaded from the session store).
657 Calling ``save()`` on a new session may also work but has a small chance of
658 generating a ``session_key`` that collides with an existing one. ``create()``
659 calls ``save()`` and loops until an unused ``session_key`` is generated.
660
661 If you're using the ``django.contrib.sessions.backends.db`` backend, each
662 session is a normal Django model. The ``Session`` model is defined in
663 :source:`django/contrib/sessions/models.py`. Because it's a normal model, you can
664 access sessions using the normal Django database API:
665
666 .. code-block:: pycon
667
668 >>> from django.contrib.sessions.models import Session
669 >>> s = Session.objects.get(pk="2b1189a188b44ad18c35e113ac6ceead")
670 >>> s.expire_date
671 datetime.datetime(2005, 8, 20, 13, 35, 12)
672
673 Note that you'll need to call
674 :meth:`~base_session.AbstractBaseSession.get_decoded()` to get the session
675 dictionary. This is necessary because the dictionary is stored in an encoded
676 format:
677
678 .. code-block:: pycon
679
680 >>> s.session_data
681 'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
682 >>> s.get_decoded()
683 {'user_id': 42}
684
685 When sessions are saved
686 =======================
687
688 By default, Django only saves to the session database when the session has been
689 modified -- that is if any of its dictionary values have been assigned or
690 deleted::
691
692 # Session is modified.
693 request.session["foo"] = "bar"
694
695 # Session is modified.
696 del request.session["foo"]
697
698 # Session is modified.
699 request.session["foo"] = {}
700
701 # Gotcha: Session is NOT modified, because this alters
702 # request.session['foo'] instead of request.session.
703 request.session["foo"]["bar"] = "baz"
704
705 In the last case of the above example, we can tell the session object
706 explicitly that it has been modified by setting the ``modified`` attribute on
707 the session object::
708
709 request.session.modified = True
710
711 To change this default behavior, set the :setting:`SESSION_SAVE_EVERY_REQUEST`
712 setting to ``True``. When set to ``True``, Django will save the session to the
713 database on every single request.
714
715 Note that the session cookie is only sent when a session has been created or
716 modified. If :setting:`SESSION_SAVE_EVERY_REQUEST` is ``True``, the session
717 cookie will be sent on every request.
718
719 Similarly, the ``expires`` part of a session cookie is updated each time the
720 session cookie is sent.
721
722 The session is not saved if the response's status code is 500.
723
724 .. _browser-length-vs-persistent-sessions:
725
726 Browser-length sessions vs. persistent sessions
727 ===============================================
728
729 You can control whether the session framework uses browser-length sessions vs.
730 persistent sessions with the :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE`
731 setting.
732
733 By default, :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` is set to ``False``,
734 which means session cookies will be stored in users' browsers for as long as
735 :setting:`SESSION_COOKIE_AGE`. Use this if you don't want people to have to
736 log in every time they open a browser.
737
738 If :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` is set to ``True``, Django will
739 use browser-length cookies -- cookies that expire as soon as the user closes
740 their browser. Use this if you want people to have to log in every time they
741 open a browser.
742
743 This setting is a global default and can be overwritten at a per-session level
744 by explicitly calling the :meth:`~backends.base.SessionBase.set_expiry` method
745 of ``request.session`` as described above in `using sessions in views`_.
746
747 .. note::
748
749 Some browsers (Chrome, for example) provide settings that allow users to
750 continue browsing sessions after closing and reopening the browser. In
751 some cases, this can interfere with the
752 :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` setting and prevent sessions
753 from expiring on browser close. Please be aware of this while testing
754 Django applications which have the
755 :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` setting enabled.
756
757 .. _clearing-the-session-store:
758
759 Clearing the session store
760 ==========================
761
762 As users create new sessions on your website, session data can accumulate in
763 your session store. If you're using the database backend, the
764 ``django_session`` database table will grow. If you're using the file backend,
765 your temporary directory will contain an increasing number of files.
766
767 To understand this problem, consider what happens with the database backend.
768 When a user logs in, Django adds a row to the ``django_session`` database
769 table. Django updates this row each time the session data changes. If the user
770 logs out manually, Django deletes the row. But if the user does *not* log out,
771 the row never gets deleted. A similar process happens with the file backend.
772
773 Django does *not* provide automatic purging of expired sessions. Therefore,
774 it's your job to purge expired sessions on a regular basis. Django provides a
775 clean-up management command for this purpose: :djadmin:`clearsessions`. It's
776 recommended to call this command on a regular basis, for example as a daily
777 cron job.
778
779 Note that the cache backend isn't vulnerable to this problem, because caches
780 automatically delete stale data. Neither is the cookie backend, because the
781 session data is stored by the users' browsers.
782
783 Settings
784 ========
785
786 A few :ref:`Django settings <settings-sessions>` give you control over session
787 behavior:
788
789 * :setting:`SESSION_CACHE_ALIAS`
790 * :setting:`SESSION_COOKIE_AGE`
791 * :setting:`SESSION_COOKIE_DOMAIN`
792 * :setting:`SESSION_COOKIE_HTTPONLY`
793 * :setting:`SESSION_COOKIE_NAME`
794 * :setting:`SESSION_COOKIE_PATH`
795 * :setting:`SESSION_COOKIE_SAMESITE`
796 * :setting:`SESSION_COOKIE_SECURE`
797 * :setting:`SESSION_ENGINE`
798 * :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE`
799 * :setting:`SESSION_FILE_PATH`
800 * :setting:`SESSION_SAVE_EVERY_REQUEST`
801 * :setting:`SESSION_SERIALIZER`
802
803 .. _topics-session-security:
804
805 Session security
806 ================
807
808 Subdomains within a site are able to set cookies on the client for the whole
809 domain. This makes session fixation possible if cookies are permitted from
810 subdomains not controlled by trusted users.
811
812 For example, an attacker could log into ``good.example.com`` and get a valid
813 session for their account. If the attacker has control over ``bad.example.com``,
814 they can use it to send their session key to you since a subdomain is permitted
815 to set cookies on ``*.example.com``. When you visit ``good.example.com``,
816 you'll be logged in as the attacker and might inadvertently enter your
817 sensitive personal data (e.g. credit card info) into the attacker's account.
818
819 Another possible attack would be if ``good.example.com`` sets its
820 :setting:`SESSION_COOKIE_DOMAIN` to ``"example.com"`` which would cause
821 session cookies from that site to be sent to ``bad.example.com``.
822
823 Technical details
824 =================
825
826 * The session dictionary accepts any :mod:`json` serializable value when using
827 :class:`~django.contrib.sessions.serializers.JSONSerializer`.
828
829 * Session data is stored in a database table named ``django_session`` .
830
831 * Django only sends a cookie if it needs to. If you don't set any session
832 data, it won't send a session cookie.
833
834 The ``SessionStore`` object
835 ---------------------------
836
837 When working with sessions internally, Django uses a session store object from
838 the corresponding session engine. By convention, the session store object class
839 is named ``SessionStore`` and is located in the module designated by
840 :setting:`SESSION_ENGINE`.
841
842 All ``SessionStore`` subclasses available in Django implement the following
843 data manipulation methods:
844
845 * ``exists()``
846 * ``create()``
847 * ``save()``
848 * ``delete()``
849 * ``load()``
850 * :meth:`~.SessionBase.clear_expired`
851
852 An asynchronous interface for these methods is provided by wrapping them with
853 ``sync_to_async()``. They can be implemented directly if an async-native
854 implementation is available:
855
856 * ``aexists()``
857 * ``acreate()``
858 * ``asave()``
859 * ``adelete()``
860 * ``aload()``
861 * :meth:`~.SessionBase.aclear_expired`
862
863 In order to build a custom session engine or to customize an existing one, you
864 may create a new class inheriting from :class:`~backends.base.SessionBase` or
865 any other existing ``SessionStore`` class.
866
867 You can extend the session engines, but doing so with database-backed session
868 engines generally requires some extra effort (see the next section for
869 details).
870
871 .. versionchanged:: 5.1
872
873 ``aexists()``, ``acreate()``, ``asave()``, ``adelete()``, ``aload()``, and
874 ``aclear_expired()`` methods were added.
875
876 .. _extending-database-backed-session-engines:
877
878 Extending database-backed session engines
879 =========================================
880
881 Creating a custom database-backed session engine built upon those included in
882 Django (namely ``db`` and ``cached_db``) may be done by inheriting
883 :class:`~base_session.AbstractBaseSession` and either ``SessionStore`` class.
884
885 ``AbstractBaseSession`` and ``BaseSessionManager`` are importable from
886 ``django.contrib.sessions.base_session`` so that they can be imported without
887 including ``django.contrib.sessions`` in :setting:`INSTALLED_APPS`.
888
889 .. class:: base_session.AbstractBaseSession
890
891
892 The abstract base session model.
893
894 .. attribute:: session_key
895
896 Primary key. The field itself may contain up to 40 characters. The
897 current implementation generates a 32-character string (a random
898 sequence of digits and lowercase ASCII letters).
899
900 .. attribute:: session_data
901
902 A string containing an encoded and serialized session dictionary.
903
904 .. attribute:: expire_date
905
906 A datetime designating when the session expires.
907
908 Expired sessions are not available to a user, however, they may still
909 be stored in the database until the :djadmin:`clearsessions` management
910 command is run.
911
912 .. classmethod:: get_session_store_class()
913
914 Returns a session store class to be used with this session model.
915
916 .. method:: get_decoded()
917
918 Returns decoded session data.
919
920 Decoding is performed by the session store class.
921
922 You can also customize the model manager by subclassing
923 :class:`~django.contrib.sessions.base_session.BaseSessionManager`:
924
925 .. class:: base_session.BaseSessionManager
926
927 .. method:: encode(session_dict)
928
929 Returns the given session dictionary serialized and encoded as a string.
930
931 Encoding is performed by the session store class tied to a model class.
932
933 .. method:: save(session_key, session_dict, expire_date)
934
935 Saves session data for a provided session key, or deletes the session
936 in case the data is empty.
937
938 Customization of ``SessionStore`` classes is achieved by overriding methods
939 and properties described below:
940
941 .. class:: backends.db.SessionStore
942
943 Implements database-backed session store.
944
945 .. classmethod:: get_model_class()
946
947 Override this method to return a custom session model if you need one.
948
949 .. method:: create_model_instance(data)
950
951 Returns a new instance of the session model object, which represents
952 the current session state.
953
954 Overriding this method provides the ability to modify session model
955 data before it's saved to database.
956
957 .. class:: backends.cached_db.SessionStore
958
959 Implements cached database-backed session store.
960
961 .. attribute:: cache_key_prefix
962
963 A prefix added to a session key to build a cache key string.
964
965 Example
966 -------
967
968 The example below shows a custom database-backed session engine that includes
969 an additional database column to store an account ID (thus providing an option
970 to query the database for all active sessions for an account)::
971
972 from django.contrib.sessions.backends.db import SessionStore as DBStore
973 from django.contrib.sessions.base_session import AbstractBaseSession
974 from django.db import models
975
976
977 class CustomSession(AbstractBaseSession):
978 account_id = models.IntegerField(null=True, db_index=True)
979
980 @classmethod
981 def get_session_store_class(cls):
982 return SessionStore
983
984
985 class SessionStore(DBStore):
986 @classmethod
987 def get_model_class(cls):
988 return CustomSession
989
990 def create_model_instance(self, data):
991 obj = super().create_model_instance(data)
992 try:
993 account_id = int(data.get("_auth_user_id"))
994 except (ValueError, TypeError):
995 account_id = None
996 obj.account_id = account_id
997 return obj
998
999 If you are migrating from the Django's built-in ``cached_db`` session store to
1000 a custom one based on ``cached_db``, you should override the cache key prefix
1001 in order to prevent a namespace clash::
1002
1003 class SessionStore(CachedDBStore):
1004 cache_key_prefix = "mysessions.custom_cached_db_backend"
1005
1006 # ...
1007
1008 Session IDs in URLs
1009 ===================
1010
1011 The Django sessions framework is entirely, and solely, cookie-based. It does
1012 not fall back to putting session IDs in URLs as a last resort, as PHP does.
1013 This is an intentional design decision. Not only does that behavior make URLs
1014 ugly, it makes your site vulnerable to session-ID theft via the "Referer"
1015 header.