2
0

sessions.txt 36 KB

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