sessions.txt 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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_CLASSES` setting and make sure
  16. it contains ``'django.contrib.sessions.middleware.SessionMiddleware'``.
  17. The default ``settings.py`` created by ``django-admin.py startproject``
  18. has ``SessionMiddleware`` activated.
  19. If you don't want to use sessions, you might as well remove the
  20. ``SessionMiddleware`` line from :setting:`MIDDLEWARE_CLASSES` and
  21. ``'django.contrib.sessions'`` from your :setting:`INSTALLED_APPS`.
  22. It'll save you a small bit of overhead.
  23. Configuring the session engine
  24. ==============================
  25. By default, Django stores sessions in your database (using the model
  26. ``django.contrib.sessions.models.Session``). Though this is convenient, in
  27. some setups it's faster to store session data elsewhere, so Django can be
  28. configured to store session data on your filesystem or in your cache.
  29. Using database-backed sessions
  30. ------------------------------
  31. If you want to use a database-backed session, you need to add
  32. ``'django.contrib.sessions'`` to your :setting:`INSTALLED_APPS` setting.
  33. Once you have configured your installation, run ``manage.py syncdb``
  34. to install the single database table that stores session data.
  35. .. _cached-sessions-backend:
  36. Using cached sessions
  37. ---------------------
  38. For better performance, you may want to use a cache-based session backend.
  39. To store session data using Django's cache system, you'll first need to make
  40. sure you've configured your cache; see the :doc:`cache documentation
  41. </topics/cache>` for details.
  42. .. warning::
  43. You should only use cache-based sessions if you're using the Memcached
  44. cache backend. The local-memory cache backend doesn't retain data long
  45. enough to be a good choice, and it'll be faster to use file or database
  46. sessions directly instead of sending everything through the file or
  47. database cache backends.
  48. If you have multiple caches defined in :setting:`CACHES`, Django will use the
  49. default cache. To use another cache, set :setting:`SESSION_CACHE_ALIAS` to the
  50. name of that cache.
  51. .. versionchanged:: 1.5
  52. The :setting:`SESSION_CACHE_ALIAS` setting was added.
  53. Once your cache is configured, you've got two choices for how to store data in
  54. the cache:
  55. * Set :setting:`SESSION_ENGINE` to
  56. ``"django.contrib.sessions.backends.cache"`` for a simple caching session
  57. store. Session data will be stored directly your cache. However, session
  58. data may not be persistent: cached data can be evicted if the cache fills
  59. up or if the cache server is restarted.
  60. * For persistent, cached data, set :setting:`SESSION_ENGINE` to
  61. ``"django.contrib.sessions.backends.cached_db"``. This uses a
  62. write-through cache -- every write to the cache will also be written to
  63. the database. Session reads only use the database if the data is not
  64. already in the cache.
  65. Both session stores are quite fast, but the simple cache is faster because it
  66. disregards persistence. In most cases, the ``cached_db`` backend will be fast
  67. enough, but if you need that last bit of performance, and are willing to let
  68. session data be expunged from time to time, the ``cache`` backend is for you.
  69. If you use the ``cached_db`` session backend, you also need to follow the
  70. configuration instructions for the `using database-backed sessions`_.
  71. Using file-based sessions
  72. -------------------------
  73. To use file-based sessions, set the :setting:`SESSION_ENGINE` setting to
  74. ``"django.contrib.sessions.backends.file"``.
  75. You might also want to set the :setting:`SESSION_FILE_PATH` setting (which
  76. defaults to output from ``tempfile.gettempdir()``, most likely ``/tmp``) to
  77. control where Django stores session files. Be sure to check that your Web
  78. server has permissions to read and write to this location.
  79. .. _cookie-session-backend:
  80. Using cookie-based sessions
  81. ---------------------------
  82. .. versionadded:: 1.4
  83. To use cookies-based sessions, set the :setting:`SESSION_ENGINE` setting to
  84. ``"django.contrib.sessions.backends.signed_cookies"``. The session data will be
  85. stored using Django's tools for :doc:`cryptographic signing </topics/signing>`
  86. and the :setting:`SECRET_KEY` setting.
  87. .. note::
  88. It's recommended to leave the :setting:`SESSION_COOKIE_HTTPONLY` setting
  89. ``True`` to prevent tampering of the stored data from JavaScript.
  90. .. warning::
  91. **The session data is signed but not encrypted**
  92. When using the cookies backend the session data can be read by the client.
  93. A MAC (Message Authentication Code) is used to protect the data against
  94. changes by the client, so that the session data will be invalidated when being
  95. tampered with. The same invalidation happens if the client storing the
  96. cookie (e.g. your user's browser) can't store all of the session cookie and
  97. drops data. Even though Django compresses the data, it's still entirely
  98. possible to exceed the `common limit of 4096 bytes`_ per cookie.
  99. **No freshness guarantee**
  100. Note also that while the MAC can guarantee the authenticity of the data
  101. (that it was generated by your site, and not someone else), and the
  102. integrity of the data (that it is all there and correct), it cannot
  103. guarantee freshness i.e. that you are being sent back the last thing you
  104. sent to the client. This means that for some uses of session data, the
  105. cookie backend might open you up to `replay attacks`_. Cookies will only be
  106. detected as 'stale' if they are older than your
  107. :setting:`SESSION_COOKIE_AGE`.
  108. **Performance**
  109. Finally, the size of a cookie can have an impact on the `speed of your site`_.
  110. .. _`common limit of 4096 bytes`: http://tools.ietf.org/html/rfc2965#section-5.3
  111. .. _`replay attacks`: http://en.wikipedia.org/wiki/Replay_attack
  112. .. _`speed of your site`: http://yuiblog.com/blog/2007/03/01/performance-research-part-3/
  113. Using sessions in views
  114. =======================
  115. When ``SessionMiddleware`` is activated, each :class:`~django.http.HttpRequest`
  116. object -- the first argument to any Django view function -- will have a
  117. ``session`` attribute, which is a dictionary-like object.
  118. You can read it and write to ``request.session`` at any point in your view.
  119. You can edit it multiple times.
  120. .. class:: backends.base.SessionBase
  121. This is the base class for all session objects. It has the following
  122. standard dictionary methods:
  123. .. method:: __getitem__(key)
  124. Example: ``fav_color = request.session['fav_color']``
  125. .. method:: __setitem__(key, value)
  126. Example: ``request.session['fav_color'] = 'blue'``
  127. .. method:: __delitem__(key)
  128. Example: ``del request.session['fav_color']``. This raises ``KeyError``
  129. if the given ``key`` isn't already in the session.
  130. .. method:: __contains__(key)
  131. Example: ``'fav_color' in request.session``
  132. .. method:: get(key, default=None)
  133. Example: ``fav_color = request.session.get('fav_color', 'red')``
  134. .. method:: pop(key)
  135. Example: ``fav_color = request.session.pop('fav_color')``
  136. .. method:: keys
  137. .. method:: items
  138. .. method:: setdefault
  139. .. method:: clear
  140. It also has these methods:
  141. .. method:: flush
  142. Delete the current session data from the session and regenerate the
  143. session key value that is sent back to the user in the cookie. This is
  144. used if you want to ensure that the previous session data can't be
  145. accessed again from the user's browser (for example, the
  146. :func:`django.contrib.auth.logout()` function calls it).
  147. .. method:: set_test_cookie
  148. Sets a test cookie to determine whether the user's browser supports
  149. cookies. Due to the way cookies work, you won't be able to test this
  150. until the user's next page request. See `Setting test cookies`_ below for
  151. more information.
  152. .. method:: test_cookie_worked
  153. Returns either ``True`` or ``False``, depending on whether the user's
  154. browser accepted the test cookie. Due to the way cookies work, you'll
  155. have to call ``set_test_cookie()`` on a previous, separate page request.
  156. See `Setting test cookies`_ below for more information.
  157. .. method:: delete_test_cookie
  158. Deletes the test cookie. Use this to clean up after yourself.
  159. .. method:: set_expiry(value)
  160. Sets the expiration time for the session. You can pass a number of
  161. different values:
  162. * If ``value`` is an integer, the session will expire after that
  163. many seconds of inactivity. For example, calling
  164. ``request.session.set_expiry(300)`` would make the session expire
  165. in 5 minutes.
  166. * If ``value`` is a ``datetime`` or ``timedelta`` object, the
  167. session will expire at that specific date/time.
  168. * If ``value`` is ``0``, the user's session cookie will expire
  169. when the user's Web browser is closed.
  170. * If ``value`` is ``None``, the session reverts to using the global
  171. session expiry policy.
  172. Reading a session is not considered activity for expiration
  173. purposes. Session expiration is computed from the last time the
  174. session was *modified*.
  175. .. method:: get_expiry_age
  176. Returns the number of seconds until this session expires. For sessions
  177. with no custom expiration (or those set to expire at browser close), this
  178. will equal :setting:`SESSION_COOKIE_AGE`.
  179. This function accepts two optional keyword arguments:
  180. - ``modification``: last modification of the session, as a
  181. :class:`~datetime.datetime` object. Defaults to the current time.
  182. - ``expiry``: expiry information for the session, as a
  183. :class:`~datetime.datetime` object, an :func:`int` (in seconds), or
  184. ``None``. Defaults to the value stored in the session by
  185. :meth:`set_expiry`, if there is one, or ``None``.
  186. .. method:: get_expiry_date
  187. Returns the date this session will expire. For sessions with no custom
  188. expiration (or those set to expire at browser close), this will equal the
  189. date :setting:`SESSION_COOKIE_AGE` seconds from now.
  190. This function accepts the same keyword argumets as :meth:`get_expiry_age`.
  191. .. method:: get_expire_at_browser_close
  192. Returns either ``True`` or ``False``, depending on whether the user's
  193. session cookie will expire when the user's Web browser is closed.
  194. .. method:: SessionBase.clear_expired
  195. .. versionadded:: 1.5
  196. Removes expired sessions from the session store. This class method is
  197. called by :djadmin:`clearsessions`.
  198. Session object guidelines
  199. -------------------------
  200. * Use normal Python strings as dictionary keys on ``request.session``. This
  201. is more of a convention than a hard-and-fast rule.
  202. * Session dictionary keys that begin with an underscore are reserved for
  203. internal use by Django.
  204. * Don't override ``request.session`` with a new object, and don't access or
  205. set its attributes. Use it like a Python dictionary.
  206. Examples
  207. --------
  208. This simplistic view sets a ``has_commented`` variable to ``True`` after a user
  209. posts a comment. It doesn't let a user post a comment more than once::
  210. def post_comment(request, new_comment):
  211. if request.session.get('has_commented', False):
  212. return HttpResponse("You've already commented.")
  213. c = comments.Comment(comment=new_comment)
  214. c.save()
  215. request.session['has_commented'] = True
  216. return HttpResponse('Thanks for your comment!')
  217. This simplistic view logs in a "member" of the site::
  218. def login(request):
  219. m = Member.objects.get(username=request.POST['username'])
  220. if m.password == request.POST['password']:
  221. request.session['member_id'] = m.id
  222. return HttpResponse("You're logged in.")
  223. else:
  224. return HttpResponse("Your username and password didn't match.")
  225. ...And this one logs a member out, according to ``login()`` above::
  226. def logout(request):
  227. try:
  228. del request.session['member_id']
  229. except KeyError:
  230. pass
  231. return HttpResponse("You're logged out.")
  232. The standard :meth:`django.contrib.auth.logout` function actually does a bit
  233. more than this to prevent inadvertent data leakage. It calls the
  234. :meth:`~backends.base.SessionBase.flush` method of ``request.session``.
  235. We are using this example as a demonstration of how to work with session
  236. objects, not as a full ``logout()`` implementation.
  237. Setting test cookies
  238. ====================
  239. As a convenience, Django provides an easy way to test whether the user's
  240. browser accepts cookies. Just call the
  241. :meth:`~backends.base.SessionBase.set_test_cookie` method of
  242. ``request.session`` in a view, and call
  243. :meth:`~backends.base.SessionBase.test_cookie_worked` in a subsequent view --
  244. not in the same view call.
  245. This awkward split between ``set_test_cookie()`` and ``test_cookie_worked()``
  246. is necessary due to the way cookies work. When you set a cookie, you can't
  247. actually tell whether a browser accepted it until the browser's next request.
  248. It's good practice to use
  249. :meth:`~backends.base.SessionBase.delete_test_cookie()` to clean up after
  250. yourself. Do this after you've verified that the test cookie worked.
  251. Here's a typical usage example::
  252. def login(request):
  253. if request.method == 'POST':
  254. if request.session.test_cookie_worked():
  255. request.session.delete_test_cookie()
  256. return HttpResponse("You're logged in.")
  257. else:
  258. return HttpResponse("Please enable cookies and try again.")
  259. request.session.set_test_cookie()
  260. return render_to_response('foo/login_form.html')
  261. Using sessions out of views
  262. ===========================
  263. An API is available to manipulate session data outside of a view::
  264. >>> from django.contrib.sessions.backends.db import SessionStore
  265. >>> import datetime
  266. >>> s = SessionStore()
  267. >>> s['last_login'] = datetime.datetime(2005, 8, 20, 13, 35, 10)
  268. >>> s.save()
  269. >>> s.session_key
  270. '2b1189a188b44ad18c35e113ac6ceead'
  271. >>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
  272. >>> s['last_login']
  273. datetime.datetime(2005, 8, 20, 13, 35, 0)
  274. In order to prevent session fixation attacks, sessions keys that don't exist
  275. are regenerated::
  276. >>> from django.contrib.sessions.backends.db import SessionStore
  277. >>> s = SessionStore(session_key='no-such-session-here')
  278. >>> s.save()
  279. >>> s.session_key
  280. 'ff882814010ccbc3c870523934fee5a2'
  281. If you're using the ``django.contrib.sessions.backends.db`` backend, each
  282. session is just a normal Django model. The ``Session`` model is defined in
  283. ``django/contrib/sessions/models.py``. Because it's a normal model, you can
  284. access sessions using the normal Django database API::
  285. >>> from django.contrib.sessions.models import Session
  286. >>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
  287. >>> s.expire_date
  288. datetime.datetime(2005, 8, 20, 13, 35, 12)
  289. Note that you'll need to call ``get_decoded()`` to get the session dictionary.
  290. This is necessary because the dictionary is stored in an encoded format::
  291. >>> s.session_data
  292. 'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
  293. >>> s.get_decoded()
  294. {'user_id': 42}
  295. When sessions are saved
  296. =======================
  297. By default, Django only saves to the session database when the session has been
  298. modified -- that is if any of its dictionary values have been assigned or
  299. deleted::
  300. # Session is modified.
  301. request.session['foo'] = 'bar'
  302. # Session is modified.
  303. del request.session['foo']
  304. # Session is modified.
  305. request.session['foo'] = {}
  306. # Gotcha: Session is NOT modified, because this alters
  307. # request.session['foo'] instead of request.session.
  308. request.session['foo']['bar'] = 'baz'
  309. In the last case of the above example, we can tell the session object
  310. explicitly that it has been modified by setting the ``modified`` attribute on
  311. the session object::
  312. request.session.modified = True
  313. To change this default behavior, set the :setting:`SESSION_SAVE_EVERY_REQUEST`
  314. setting to ``True``. When set to ``True``, Django will save the session to the
  315. database on every single request.
  316. Note that the session cookie is only sent when a session has been created or
  317. modified. If :setting:`SESSION_SAVE_EVERY_REQUEST` is ``True``, the session
  318. cookie will be sent on every request.
  319. Similarly, the ``expires`` part of a session cookie is updated each time the
  320. session cookie is sent.
  321. .. versionchanged:: 1.5
  322. The session is not saved if the response's status code is 500.
  323. Browser-length sessions vs. persistent sessions
  324. ===============================================
  325. You can control whether the session framework uses browser-length sessions vs.
  326. persistent sessions with the :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE`
  327. setting.
  328. By default, :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` is set to ``False``,
  329. which means session cookies will be stored in users' browsers for as long as
  330. :setting:`SESSION_COOKIE_AGE`. Use this if you don't want people to have to
  331. log in every time they open a browser.
  332. If :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` is set to ``True``, Django will
  333. use browser-length cookies -- cookies that expire as soon as the user closes
  334. his or her browser. Use this if you want people to have to log in every time
  335. they open a browser.
  336. This setting is a global default and can be overwritten at a per-session level
  337. by explicitly calling the :meth:`~backends.base.SessionBase.set_expiry` method
  338. of ``request.session`` as described above in `using sessions in views`_.
  339. Clearing the session store
  340. ==========================
  341. As users create new sessions on your website, session data can accumulate in
  342. your session store. If you're using the database backend, the
  343. ``django_session`` database table will grow. If you're using the file backend,
  344. your temporary directory will contain an increasing number of files.
  345. To understand this problem, consider what happens with the database backend.
  346. When a user logs in, Django adds a row to the ``django_session`` database
  347. table. Django updates this row each time the session data changes. If the user
  348. logs out manually, Django deletes the row. But if the user does *not* log out,
  349. the row never gets deleted. A similar process happens with the file backend.
  350. Django does *not* provide automatic purging of expired sessions. Therefore,
  351. it's your job to purge expired sessions on a regular basis. Django provides a
  352. clean-up management command for this purpose: :djadmin:`clearsessions`. It's
  353. recommended to call this command on a regular basis, for example as a daily
  354. cron job.
  355. Note that the cache backend isn't vulnerable to this problem, because caches
  356. automatically delete stale data. Neither is the cookie backend, because the
  357. session data is stored by the users' browsers.
  358. Settings
  359. ========
  360. A few :doc:`Django settings </ref/settings>` give you control over session
  361. behavior:
  362. SESSION_ENGINE
  363. --------------
  364. Default: ``django.contrib.sessions.backends.db``
  365. Controls where Django stores session data. Valid values are:
  366. * ``'django.contrib.sessions.backends.db'``
  367. * ``'django.contrib.sessions.backends.file'``
  368. * ``'django.contrib.sessions.backends.cache'``
  369. * ``'django.contrib.sessions.backends.cached_db'``
  370. * ``'django.contrib.sessions.backends.signed_cookies'``
  371. See `configuring the session engine`_ for more details.
  372. SESSION_FILE_PATH
  373. -----------------
  374. Default: ``/tmp/``
  375. If you're using file-based session storage, this sets the directory in
  376. which Django will store session data.
  377. SESSION_COOKIE_AGE
  378. ------------------
  379. Default: ``1209600`` (2 weeks, in seconds)
  380. The age of session cookies, in seconds.
  381. SESSION_COOKIE_DOMAIN
  382. ---------------------
  383. Default: ``None``
  384. The domain to use for session cookies. Set this to a string such as
  385. ``".example.com"`` (note the leading dot!) for cross-domain cookies, or use
  386. ``None`` for a standard domain cookie.
  387. SESSION_COOKIE_HTTPONLY
  388. -----------------------
  389. Default: ``True``
  390. Whether to use HTTPOnly flag on the session cookie. If this is set to
  391. ``True``, client-side JavaScript will not to be able to access the
  392. session cookie.
  393. HTTPOnly_ is a flag included in a Set-Cookie HTTP response header. It
  394. is not part of the :rfc:`2109` standard for cookies, and it isn't honored
  395. consistently by all browsers. However, when it is honored, it can be a
  396. useful way to mitigate the risk of client side script accessing the
  397. protected cookie data.
  398. .. versionchanged:: 1.4
  399. The default value of the setting was changed from ``False`` to ``True``.
  400. .. _HTTPOnly: https://www.owasp.org/index.php/HTTPOnly
  401. SESSION_COOKIE_NAME
  402. -------------------
  403. Default: ``'sessionid'``
  404. The name of the cookie to use for sessions. This can be whatever you want.
  405. SESSION_COOKIE_PATH
  406. -------------------
  407. Default: ``'/'``
  408. The path set on the session cookie. This should either match the URL path of
  409. your Django installation or be parent of that path.
  410. This is useful if you have multiple Django instances running under the same
  411. hostname. They can use different cookie paths, and each instance will only see
  412. its own session cookie.
  413. SESSION_COOKIE_SECURE
  414. ---------------------
  415. Default: ``False``
  416. Whether to use a secure cookie for the session cookie. If this is set to
  417. ``True``, the cookie will be marked as "secure," which means browsers may
  418. ensure that the cookie is only sent under an HTTPS connection.
  419. SESSION_EXPIRE_AT_BROWSER_CLOSE
  420. -------------------------------
  421. Default: ``False``
  422. Whether to expire the session when the user closes his or her browser. See
  423. "Browser-length sessions vs. persistent sessions" above.
  424. SESSION_SAVE_EVERY_REQUEST
  425. --------------------------
  426. Default: ``False``
  427. Whether to save the session data on every request. If this is ``False``
  428. (default), then the session data will only be saved if it has been modified --
  429. that is, if any of its dictionary values have been assigned or deleted.
  430. .. _Django settings: ../settings/
  431. Technical details
  432. =================
  433. * The session dictionary should accept any pickleable Python object. See
  434. the :mod:`pickle` module for more information.
  435. * Session data is stored in a database table named ``django_session`` .
  436. * Django only sends a cookie if it needs to. If you don't set any session
  437. data, it won't send a session cookie.
  438. Session IDs in URLs
  439. ===================
  440. The Django sessions framework is entirely, and solely, cookie-based. It does
  441. not fall back to putting session IDs in URLs as a last resort, as PHP does.
  442. This is an intentional design decision. Not only does that behavior make URLs
  443. ugly, it makes your site vulnerable to session-ID theft via the "Referer"
  444. header.