sessions.txt 16 KB

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