sessions.txt 19 KB

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