middleware.txt 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. .. _ref-middleware:
  2. =============================
  3. Built-in middleware reference
  4. =============================
  5. .. module:: django.middleware
  6. :synopsis: Django's built-in middleware classes.
  7. This document explains all middleware components that come with Django. For
  8. information on how how to use them and how to write your own middleware, see the
  9. :ref:`middleware usage guide <topics-http-middleware>`.
  10. Available middleware
  11. ====================
  12. Cache middleware
  13. ----------------
  14. .. module:: django.middleware.cache
  15. :synopsis: Middleware for the site-wide cache
  16. .. class:: django.middleware.cache.UpdateCacheMiddleware
  17. .. class:: django.middleware.cache.FetchFromCacheMiddleware
  18. Enable the site-wide cache. If these are enabled, each Django-powered page will
  19. be cached for as long as the :setting:`CACHE_MIDDLEWARE_SECONDS` setting
  20. defines. See the :ref:`cache documentation <topics-cache>`.
  21. "Common" middleware
  22. -------------------
  23. .. module:: django.middleware.common
  24. :synopsis: Middleware adding "common" conveniences for perfectionists.
  25. .. class:: django.middleware.common.CommonMiddleware
  26. Adds a few conveniences for perfectionists:
  27. * Forbids access to user agents in the :setting:`DISALLOWED_USER_AGENTS`
  28. setting, which should be a list of strings.
  29. * Performs URL rewriting based on the :setting:`APPEND_SLASH` and
  30. :setting:`PREPEND_WWW` settings.
  31. If :setting:`APPEND_SLASH` is ``True`` and the initial URL doesn't end
  32. with a slash, and it is not found in the URLconf, then a new URL is formed
  33. by appending a slash at the end. If this new URL is found in the URLconf,
  34. then Django redirects the request to this new URL. Otherwise, the initial
  35. URL is processed as usual.
  36. For example, ``foo.com/bar`` will be redirected to ``foo.com/bar/`` if you
  37. don't have a valid URL pattern for ``foo.com/bar`` but *do* have a valid
  38. pattern for ``foo.com/bar/``.
  39. .. versionchanged:: 1.0
  40. The behavior of :setting:`APPEND_SLASH` has changed slightly in this
  41. version. It didn't used to check whether the pattern was matched in
  42. the URLconf.
  43. If :setting:`PREPEND_WWW` is ``True``, URLs that lack a leading "www."
  44. will be redirected to the same URL with a leading "www."
  45. Both of these options are meant to normalize URLs. The philosophy is that
  46. each URL should exist in one, and only one, place. Technically a URL
  47. ``foo.com/bar`` is distinct from ``foo.com/bar/`` -- a search-engine
  48. indexer would treat them as separate URLs -- so it's best practice to
  49. normalize URLs.
  50. * Handles ETags based on the :setting:`USE_ETAGS` setting. If
  51. :setting:`USE_ETAGS` is set to ``True``, Django will calculate an ETag for
  52. each request by MD5-hashing the page content, and it'll take care of
  53. sending ``Not Modified`` responses, if appropriate.
  54. View metadata middleware
  55. ------------------------
  56. .. module:: django.middleware.doc
  57. :synopsis: Middleware to help your app self-document.
  58. .. class:: django.middleware.doc.XViewMiddleware
  59. Sends custom ``X-View`` HTTP headers to HEAD requests that come from IP
  60. addresses defined in the :setting:`INTERNAL_IPS` setting. This is used by
  61. Django's automatic documentation system.
  62. GZIP middleware
  63. ---------------
  64. .. module:: django.middleware.gzip
  65. :synopsis: Middleware to serve gziped content for performance.
  66. .. class:: django.middleware.gzip.GZipMiddleware
  67. Compresses content for browsers that understand gzip compression (all modern
  68. browsers).
  69. It is suggested to place this first in the middleware list, so that the
  70. compression of the response content is the last thing that happens. Will not
  71. compress content bodies less than 200 bytes long, when the response code is
  72. something other than 200, JavaScript files (for IE compatibility), or
  73. responses that have the ``Content-Encoding`` header already specified.
  74. Conditional GET middleware
  75. --------------------------
  76. .. module:: django.middleware.http
  77. :synopsis: Middleware handling advanced HTTP features.
  78. .. class:: django.middleware.http.ConditionalGetMiddleware
  79. Handles conditional GET operations. If the response has a ``ETag`` or
  80. ``Last-Modified`` header, and the request has ``If-None-Match`` or
  81. ``If-Modified-Since``, the response is replaced by an
  82. :class:`~django.http.HttpNotModified`.
  83. Also sets the ``Date`` and ``Content-Length`` response-headers.
  84. Reverse proxy middleware
  85. ------------------------
  86. .. class:: django.middleware.http.SetRemoteAddrFromForwardedFor
  87. Sets ``request.META['REMOTE_ADDR']`` based on
  88. ``request.META['HTTP_X_FORWARDED_FOR']``, if the latter is set. This is useful
  89. if you're sitting behind a reverse proxy that causes each request's
  90. ``REMOTE_ADDR`` to be set to ``127.0.0.1``.
  91. **Important note:** This does NOT validate ``HTTP_X_FORWARDED_FOR``. If you're
  92. not behind a reverse proxy that sets ``HTTP_X_FORWARDED_FOR`` automatically, do
  93. not use this middleware. Anybody can spoof the value of
  94. ``HTTP_X_FORWARDED_FOR``, and because this sets ``REMOTE_ADDR`` based on
  95. ``HTTP_X_FORWARDED_FOR``, that means anybody can "fake" their IP address. Only
  96. use this when you can absolutely trust the value of ``HTTP_X_FORWARDED_FOR``.
  97. Locale middleware
  98. -----------------
  99. .. module:: django.middleware.locale
  100. :synopsis: Middleware to enable language selection based on the request.
  101. .. class:: django.middleware.locale.LocaleMiddleware
  102. Enables language selection based on data from the request. It customizes content
  103. for each user. See the :ref:`internationalization documentation <topics-i18n>`.
  104. Session middleware
  105. ------------------
  106. .. module:: django.contrib.sessions.middleware
  107. :synopsis: Session middleware.
  108. .. class:: django.contrib.sessions.middleware.SessionMiddleware
  109. Enables session support. See the :ref:`session documentation
  110. <topics-http-sessions>`.
  111. Authentication middleware
  112. -------------------------
  113. .. module:: django.contrib.auth.middleware
  114. :synopsis: Authentication middleware
  115. .. class:: django.contrib.auth.middleware.AuthenticationMiddleware
  116. Adds the ``user`` attribute, representing the currently-logged-in user, to every
  117. incoming ``HttpRequest`` object. See :ref:` Authentication in Web requests
  118. <topics-http-auth>`.
  119. CSRF protection middleware
  120. --------------------------
  121. .. module:: django.contrib.csrf.middleware
  122. :synopsis: Middleware adding protection against Cross Site Request Forgeries.
  123. .. class:: django.contrib.csrf.middleware.CsrfMiddleware
  124. .. versionadded:: 1.0
  125. Adds protection against Cross Site Request Forgeries by adding hidden form
  126. fields to POST forms and checking requests for the correct value. See the
  127. :ref:`Cross Site Request Forgery protection documentation <ref-contrib-csrf>`.
  128. Transaction middleware
  129. ----------------------
  130. .. module:: django.middleware.transaction
  131. :synopsis: Middleware binding a database transaction to each web request.
  132. .. class:: django.middleware.transaction.TransactionMiddleware
  133. Binds commit and rollback to the request/response phase. If a view function runs
  134. successfully, a commit is done. If it fails with an exception, a rollback is
  135. done.
  136. The order of this middleware in the stack is important: middleware modules
  137. running outside of it run with commit-on-save - the default Django behavior.
  138. Middleware modules running inside it (coming later in the stack) will be under
  139. the same transaction control as the view functions.
  140. See the :ref:`transaction management documentation <topics-db-transactions>`.