PageRenderTime 52ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/topics/http/sessions.txt

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