sessions.txt 20 KB

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