sessions.txt 21 KB

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