sessions.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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 syncdb``
  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. 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-vs-persistent-sessions:
  324. Browser-length sessions vs. persistent sessions
  325. ===============================================
  326. You can control whether the session framework uses browser-length sessions vs.
  327. persistent sessions with the :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE`
  328. setting.
  329. By default, :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` is set to ``False``,
  330. which means session cookies will be stored in users' browsers for as long as
  331. :setting:`SESSION_COOKIE_AGE`. Use this if you don't want people to have to
  332. log in every time they open a browser.
  333. If :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` is set to ``True``, Django will
  334. use browser-length cookies -- cookies that expire as soon as the user closes
  335. his or her browser. Use this if you want people to have to log in every time
  336. they open a browser.
  337. This setting is a global default and can be overwritten at a per-session level
  338. by explicitly calling the :meth:`~backends.base.SessionBase.set_expiry` method
  339. of ``request.session`` as described above in `using sessions in views`_.
  340. .. note::
  341. Some browsers (Chrome, for example) provide settings that allow users to
  342. continue browsing sessions after closing and re-opening the browser. In
  343. some cases, this can interfere with the
  344. :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` setting and prevent sessions
  345. from expiring on browser close. Please be aware of this while testing
  346. Django applications which have the
  347. :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` setting enabled.
  348. Clearing the session store
  349. ==========================
  350. As users create new sessions on your website, session data can accumulate in
  351. your session store. If you're using the database backend, the
  352. ``django_session`` database table will grow. If you're using the file backend,
  353. your temporary directory will contain an increasing number of files.
  354. To understand this problem, consider what happens with the database backend.
  355. When a user logs in, Django adds a row to the ``django_session`` database
  356. table. Django updates this row each time the session data changes. If the user
  357. logs out manually, Django deletes the row. But if the user does *not* log out,
  358. the row never gets deleted. A similar process happens with the file backend.
  359. Django does *not* provide automatic purging of expired sessions. Therefore,
  360. it's your job to purge expired sessions on a regular basis. Django provides a
  361. clean-up management command for this purpose: :djadmin:`clearsessions`. It's
  362. recommended to call this command on a regular basis, for example as a daily
  363. cron job.
  364. Note that the cache backend isn't vulnerable to this problem, because caches
  365. automatically delete stale data. Neither is the cookie backend, because the
  366. session data is stored by the users' browsers.
  367. Settings
  368. ========
  369. A few :ref:`Django settings <settings-sessions>` give you control over session
  370. behavior:
  371. * :setting:`SESSION_CACHE_ALIAS`
  372. * :setting:`SESSION_COOKIE_AGE`
  373. * :setting:`SESSION_COOKIE_DOMAIN`
  374. * :setting:`SESSION_COOKIE_HTTPONLY`
  375. * :setting:`SESSION_COOKIE_NAME`
  376. * :setting:`SESSION_COOKIE_PATH`
  377. * :setting:`SESSION_COOKIE_SECURE`
  378. * :setting:`SESSION_ENGINE`
  379. * :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE`
  380. * :setting:`SESSION_FILE_PATH`
  381. * :setting:`SESSION_SAVE_EVERY_REQUEST`
  382. Technical details
  383. =================
  384. * The session dictionary should accept any pickleable Python object. See
  385. the :mod:`pickle` module for more information.
  386. * Session data is stored in a database table named ``django_session`` .
  387. * Django only sends a cookie if it needs to. If you don't set any session
  388. data, it won't send a session cookie.
  389. Session IDs in URLs
  390. ===================
  391. The Django sessions framework is entirely, and solely, cookie-based. It does
  392. not fall back to putting session IDs in URLs as a last resort, as PHP does.
  393. This is an intentional design decision. Not only does that behavior make URLs
  394. ugly, it makes your site vulnerable to session-ID theft via the "Referer"
  395. header.