middleware.txt 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. ==========
  2. Middleware
  3. ==========
  4. .. module:: django.middleware
  5. :synopsis: Django's built-in middleware classes.
  6. This document explains all middleware components that come with Django. For
  7. information on how to use them and how to write your own middleware, see
  8. the :doc:`middleware usage guide </topics/http/middleware>`.
  9. Available middleware
  10. ====================
  11. Cache middleware
  12. ----------------
  13. .. module:: django.middleware.cache
  14. :synopsis: Middleware for the site-wide cache.
  15. .. class:: UpdateCacheMiddleware
  16. .. class:: FetchFromCacheMiddleware
  17. Enable the site-wide cache. If these are enabled, each Django-powered page will
  18. be cached for as long as the :setting:`CACHE_MIDDLEWARE_SECONDS` setting
  19. defines. See the :doc:`cache documentation </topics/cache>`.
  20. "Common" middleware
  21. -------------------
  22. .. module:: django.middleware.common
  23. :synopsis: Middleware adding "common" conveniences for perfectionists.
  24. .. class:: CommonMiddleware
  25. Adds a few conveniences for perfectionists:
  26. * Forbids access to user agents in the :setting:`DISALLOWED_USER_AGENTS`
  27. setting, which should be a list of compiled regular expression objects.
  28. * Performs URL rewriting based on the :setting:`APPEND_SLASH` and
  29. :setting:`PREPEND_WWW` settings.
  30. If :setting:`APPEND_SLASH` is ``True`` and the initial URL doesn't end
  31. with a slash, and it is not found in the URLconf, then a new URL is
  32. formed by appending a slash at the end. If this new URL is found in the
  33. URLconf, then Django redirects the request to this new URL. Otherwise,
  34. the initial URL is processed as usual.
  35. For example, ``foo.com/bar`` will be redirected to ``foo.com/bar/`` if
  36. you don't have a valid URL pattern for ``foo.com/bar`` but *do* have a
  37. valid pattern for ``foo.com/bar/``.
  38. If :setting:`PREPEND_WWW` is ``True``, URLs that lack a leading "www."
  39. will be redirected to the same URL with a leading "www."
  40. Both of these options are meant to normalize URLs. The philosophy is that
  41. each URL should exist in one, and only one, place. Technically a URL
  42. ``foo.com/bar`` is distinct from ``foo.com/bar/`` -- a search-engine
  43. indexer would treat them as separate URLs -- so it's best practice to
  44. normalize URLs.
  45. * Handles ETags based on the :setting:`USE_ETAGS` setting. If
  46. :setting:`USE_ETAGS` is set to ``True``, Django will calculate an ETag
  47. for each request by MD5-hashing the page content, and it'll take care of
  48. sending ``Not Modified`` responses, if appropriate.
  49. .. class:: BrokenLinkEmailsMiddleware
  50. * Sends broken link notification emails to :setting:`MANAGERS` (see
  51. :doc:`/howto/error-reporting`).
  52. GZip middleware
  53. ---------------
  54. .. module:: django.middleware.gzip
  55. :synopsis: Middleware to serve GZipped content for performance.
  56. .. class:: GZipMiddleware
  57. .. warning::
  58. Security researchers recently revealed that when compression techniques
  59. (including ``GZipMiddleware``) are used on a website, the site becomes
  60. exposed to a number of possible attacks. These approaches can be used to
  61. compromise, among other things, Django's CSRF protection. Before using
  62. ``GZipMiddleware`` on your site, you should consider very carefully whether
  63. you are subject to these attacks. If you're in *any* doubt about whether
  64. you're affected, you should avoid using ``GZipMiddleware``. For more
  65. details, see the `the BREACH paper (PDF)`_ and `breachattack.com`_.
  66. .. _the BREACH paper (PDF): http://breachattack.com/resources/BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf
  67. .. _breachattack.com: http://breachattack.com
  68. Compresses content for browsers that understand GZip compression (all modern
  69. browsers).
  70. This middleware should be placed before any other middleware that need to
  71. read or write the response body so that compression happens afterward.
  72. It will NOT compress content if any of the following are true:
  73. * The content body is less than 200 bytes long.
  74. * The response has already set the ``Content-Encoding`` header.
  75. * The request (the browser) hasn't sent an ``Accept-Encoding`` header
  76. containing ``gzip``.
  77. * The request is from Internet Explorer and the ``Content-Type`` header
  78. contains ``javascript`` or starts with anything other than ``text/``.
  79. We do this to avoid a bug in early versions of IE that caused decompression
  80. not to be performed on certain content types.
  81. You can apply GZip compression to individual views using the
  82. :func:`~django.views.decorators.gzip.gzip_page()` decorator.
  83. Conditional GET middleware
  84. --------------------------
  85. .. module:: django.middleware.http
  86. :synopsis: Middleware handling advanced HTTP features.
  87. .. class:: ConditionalGetMiddleware
  88. Handles conditional GET operations. If the response has a ``ETag`` or
  89. ``Last-Modified`` header, and the request has ``If-None-Match`` or
  90. ``If-Modified-Since``, the response is replaced by an
  91. :class:`~django.http.HttpResponseNotModified`.
  92. Also sets the ``Date`` and ``Content-Length`` response-headers.
  93. Reverse proxy middleware
  94. ------------------------
  95. .. class:: SetRemoteAddrFromForwardedFor
  96. This middleware was removed in Django 1.1. See :ref:`the release notes
  97. <removed-setremoteaddrfromforwardedfor-middleware>` for details.
  98. Locale middleware
  99. -----------------
  100. .. module:: django.middleware.locale
  101. :synopsis: Middleware to enable language selection based on the request.
  102. .. class:: LocaleMiddleware
  103. Enables language selection based on data from the request. It customizes
  104. content for each user. See the :doc:`internationalization documentation
  105. </topics/i18n/translation>`.
  106. .. attribute:: LocaleMiddleware.response_redirect_class
  107. Defaults to :class:`~django.http.HttpResponseRedirect`. Subclass
  108. ``LocaleMiddleware`` and override the attribute to customize the redirects
  109. issued by the middleware.
  110. Message middleware
  111. ------------------
  112. .. module:: django.contrib.messages.middleware
  113. :synopsis: Message middleware.
  114. .. class:: MessageMiddleware
  115. Enables cookie- and session-based message support. See the
  116. :doc:`messages documentation </ref/contrib/messages>`.
  117. Session middleware
  118. ------------------
  119. .. module:: django.contrib.sessions.middleware
  120. :synopsis: Session middleware.
  121. .. class:: SessionMiddleware
  122. Enables session support. See the :doc:`session documentation
  123. </topics/http/sessions>`.
  124. Site middleware
  125. ---------------
  126. .. module:: django.contrib.sites.middleware
  127. :synopsis: Site middleware.
  128. .. class:: CurrentSiteMiddleware
  129. .. versionadded:: 1.7
  130. Adds the ``site`` attribute representing the current site to every incoming
  131. ``HttpRequest`` object. See the :ref:`sites documentation <site-middleware>`.
  132. Authentication middleware
  133. -------------------------
  134. .. module:: django.contrib.auth.middleware
  135. :synopsis: Authentication middleware.
  136. .. class:: AuthenticationMiddleware
  137. Adds the ``user`` attribute, representing the currently-logged-in user, to
  138. every incoming ``HttpRequest`` object. See :ref:`Authentication in Web requests
  139. <auth-web-requests>`.
  140. CSRF protection middleware
  141. --------------------------
  142. .. module:: django.middleware.csrf
  143. :synopsis: Middleware adding protection against Cross Site Request
  144. Forgeries.
  145. .. class:: CsrfViewMiddleware
  146. Adds protection against Cross Site Request Forgeries by adding hidden form
  147. fields to POST forms and checking requests for the correct value. See the
  148. :doc:`Cross Site Request Forgery protection documentation </ref/contrib/csrf>`.
  149. Transaction middleware
  150. ----------------------
  151. .. module:: django.middleware.transaction
  152. :synopsis: Middleware binding a database transaction to each Web request.
  153. .. class:: TransactionMiddleware
  154. .. versionchanged:: 1.6
  155. ``TransactionMiddleware`` is deprecated. The documentation of transactions
  156. contains :ref:`upgrade instructions <transactions-upgrading-from-1.5>`.
  157. Binds commit and rollback of the default database to the request/response
  158. phase. If a view function runs successfully, a commit is done. If it fails with
  159. an exception, a rollback is done.
  160. The order of this middleware in the stack is important: middleware modules
  161. running outside of it run with commit-on-save - the default Django behavior.
  162. Middleware modules running inside it (coming later in the stack) will be under
  163. the same transaction control as the view functions.
  164. See the :doc:`transaction management documentation </topics/db/transactions>`.
  165. X-Frame-Options middleware
  166. --------------------------
  167. .. module:: django.middleware.clickjacking
  168. :synopsis: Clickjacking protection
  169. .. class:: XFrameOptionsMiddleware
  170. Simple :doc:`clickjacking protection via the X-Frame-Options header </ref/clickjacking/>`.