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