middleware.txt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. ==========
  2. Middleware
  3. ==========
  4. Middleware is a framework of hooks into Django's request/response processing.
  5. It's a light, low-level "plugin" system for globally altering Django's input
  6. and/or output.
  7. Each middleware component is responsible for doing some specific function. For
  8. example, Django includes a middleware component, ``XViewMiddleware``, that adds
  9. an ``"X-View"`` HTTP header to every response to a ``HEAD`` request.
  10. This document explains all middleware components that come with Django, how to
  11. use them, and how to write your own middleware.
  12. Activating middleware
  13. =====================
  14. To activate a middleware component, add it to the ``MIDDLEWARE_CLASSES`` list
  15. in your Django settings. In ``MIDDLEWARE_CLASSES``, each middleware component
  16. is represented by a string: the full Python path to the middleware's class
  17. name. For example, here's the default ``MIDDLEWARE_CLASSES`` created by
  18. ``django-admin.py startproject``::
  19. MIDDLEWARE_CLASSES = (
  20. 'django.middleware.common.CommonMiddleware',
  21. 'django.contrib.sessions.middleware.SessionMiddleware',
  22. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  23. 'django.middleware.doc.XViewMiddleware',
  24. )
  25. Django applies middleware in the order it's defined in ``MIDDLEWARE_CLASSES``,
  26. except in the case of response and exception middleware, which is applied in
  27. reverse order.
  28. A Django installation doesn't require any middleware -- e.g.,
  29. ``MIDDLEWARE_CLASSES`` can be empty, if you'd like -- but it's strongly
  30. suggested that you use ``CommonMiddleware``.
  31. Available middleware
  32. ====================
  33. django.middleware.cache.CacheMiddleware
  34. ---------------------------------------
  35. Enables site-wide cache. If this is enabled, each Django-powered page will be
  36. cached for as long as the ``CACHE_MIDDLEWARE_SECONDS`` setting defines. See
  37. the `cache documentation`_.
  38. .. _`cache documentation`: ../cache/#the-per-site-cache
  39. django.middleware.common.CommonMiddleware
  40. -----------------------------------------
  41. Adds a few conveniences for perfectionists:
  42. * Forbids access to user agents in the ``DISALLOWED_USER_AGENTS`` setting,
  43. which should be a list of strings.
  44. * Performs URL rewriting based on the ``APPEND_SLASH`` and ``PREPEND_WWW``
  45. settings.
  46. If ``APPEND_SLASH`` is ``True`` and the initial URL doesn't end with a slash,
  47. and it is not found in the URLconf, then a new URL is formed by appending a
  48. slash at the end. If this new URL is found in the URLconf, then Django
  49. redirects the request to this new URL. Otherwise, the initial URL is
  50. processed as usual.
  51. For example, ``foo.com/bar`` will be redirected to ``foo.com/bar/`` if you
  52. don't have a valid URL pattern for ``foo.com/bar`` but *do* have a valid
  53. pattern for ``foo.com/bar/``.
  54. **New in Django development version:** The behavior of ``APPEND_SLASH`` has
  55. changed slightly in the development version. It didn't used to check whether
  56. the pattern was matched in the URLconf.
  57. If ``PREPEND_WWW`` is ``True``, URLs that lack a leading "www." will be
  58. redirected to the same URL with a leading "www."
  59. Both of these options are meant to normalize URLs. The philosophy is that
  60. each URL should exist in one, and only one, place. Technically a URL
  61. ``foo.com/bar`` is distinct from ``foo.com/bar/`` -- a search-engine
  62. indexer would treat them as separate URLs -- so it's best practice to
  63. normalize URLs.
  64. * Handles ETags based on the ``USE_ETAGS`` setting. If ``USE_ETAGS`` is set
  65. to ``True``, Django will calculate an ETag for each request by
  66. MD5-hashing the page content, and it'll take care of sending
  67. ``Not Modified`` responses, if appropriate.
  68. django.middleware.doc.XViewMiddleware
  69. -------------------------------------
  70. Sends custom ``X-View`` HTTP headers to HEAD requests that come from IP
  71. addresses defined in the ``INTERNAL_IPS`` setting. This is used by Django's
  72. automatic documentation system.
  73. django.middleware.gzip.GZipMiddleware
  74. -------------------------------------
  75. Compresses content for browsers that understand gzip compression (all modern
  76. browsers).
  77. It is suggested to place this first in the middleware list, so that the
  78. compression of the response content is the last thing that happens. Will not
  79. compress content bodies less than 200 bytes long, when the response code is
  80. something other than 200, JavaScript files (for IE compatibitility), or
  81. responses that have the ``Content-Encoding`` header already specified.
  82. django.middleware.http.ConditionalGetMiddleware
  83. -----------------------------------------------
  84. Handles conditional GET operations. If the response has a ``ETag`` or
  85. ``Last-Modified`` header, and the request has ``If-None-Match`` or
  86. ``If-Modified-Since``, the response is replaced by an HttpNotModified.
  87. Also sets the ``Date`` and ``Content-Length`` response-headers.
  88. django.middleware.http.SetRemoteAddrFromForwardedFor
  89. ----------------------------------------------------
  90. Sets ``request.META['REMOTE_ADDR']`` based on
  91. ``request.META['HTTP_X_FORWARDED_FOR']``, if the latter is set. This is useful
  92. if you're sitting behind a reverse proxy that causes each request's
  93. ``REMOTE_ADDR`` to be set to ``127.0.0.1``.
  94. **Important note:** This does NOT validate ``HTTP_X_FORWARDED_FOR``. If you're
  95. not behind a reverse proxy that sets ``HTTP_X_FORWARDED_FOR`` automatically, do
  96. not use this middleware. Anybody can spoof the value of
  97. ``HTTP_X_FORWARDED_FOR``, and because this sets ``REMOTE_ADDR`` based on
  98. ``HTTP_X_FORWARDED_FOR``, that means anybody can "fake" their IP address. Only
  99. use this when you can absolutely trust the value of ``HTTP_X_FORWARDED_FOR``.
  100. django.middleware.locale.LocaleMiddleware
  101. -----------------------------------------
  102. Enables language selection based on data from the request. It customizes content
  103. for each user. See the `internationalization documentation`_.
  104. .. _`internationalization documentation`: ../i18n/
  105. django.contrib.sessions.middleware.SessionMiddleware
  106. ----------------------------------------------------
  107. Enables session support. See the `session documentation`_.
  108. .. _`session documentation`: ../sessions/
  109. django.contrib.auth.middleware.AuthenticationMiddleware
  110. -------------------------------------------------------
  111. Adds the ``user`` attribute, representing the currently-logged-in user, to
  112. every incoming ``HttpRequest`` object. See `Authentication in Web requests`_.
  113. .. _Authentication in Web requests: ../authentication/#authentication-in-web-requests
  114. django.contrib.csrf.middleware.CsrfMiddleware
  115. ---------------------------------------------
  116. **New in Django development version**
  117. Adds protection against Cross Site Request Forgeries by adding hidden form
  118. fields to POST forms and checking requests for the correct value. See the
  119. `Cross Site Request Forgery protection documentation`_.
  120. .. _`Cross Site Request Forgery protection documentation`: ../csrf/
  121. django.middleware.transaction.TransactionMiddleware
  122. ---------------------------------------------------
  123. Binds commit and rollback to the request/response phase. If a view function runs
  124. successfully, a commit is done. If it fails with an exception, a rollback is
  125. done.
  126. The order of this middleware in the stack is important: middleware modules
  127. running outside of it run with commit-on-save - the default Django behavior.
  128. Middleware modules running inside it (coming later in the stack) will be under
  129. the same transaction control as the view functions.
  130. See the `transaction management documentation`_.
  131. .. _`transaction management documentation`: ../transactions/
  132. Writing your own middleware
  133. ===========================
  134. Writing your own middleware is easy. Each middleware component is a single
  135. Python class that defines one or more of the following methods:
  136. ``process_request``
  137. -------------------
  138. Interface: ``process_request(self, request)``
  139. ``request`` is an ``HttpRequest`` object. This method is called on each
  140. request, before Django decides which view to execute.
  141. ``process_request()`` should return either ``None`` or an ``HttpResponse``
  142. object. If it returns ``None``, Django will continue processing this request,
  143. executing any other middleware and, then, the appropriate view. If it returns
  144. an ``HttpResponse`` object, Django won't bother calling ANY other request,
  145. view or exception middleware, or the appropriate view; it'll return that
  146. ``HttpResponse``. Response middleware is always called on every response.
  147. ``process_view``
  148. ----------------
  149. Interface: ``process_view(self, request, view_func, view_args, view_kwargs)``
  150. ``request`` is an ``HttpRequest`` object. ``view_func`` is the Python function
  151. that Django is about to use. (It's the actual function object, not the name of
  152. the function as a string.) ``view_args`` is a list of positional arguments that
  153. will be passed to the view, and ``view_kwargs`` is a dictionary of keyword
  154. arguments that will be passed to the view. Neither ``view_args`` nor
  155. ``view_kwargs`` include the first view argument (``request``).
  156. ``process_view()`` is called just before Django calls the view. It should
  157. return either ``None`` or an ``HttpResponse`` object. If it returns ``None``,
  158. Django will continue processing this request, executing any other
  159. ``process_view()`` middleware and, then, the appropriate view. If it returns an
  160. ``HttpResponse`` object, Django won't bother calling ANY other request, view
  161. or exception middleware, or the appropriate view; it'll return that
  162. ``HttpResponse``. Response middleware is always called on every response.
  163. ``process_response``
  164. --------------------
  165. Interface: ``process_response(self, request, response)``
  166. ``request`` is an ``HttpRequest`` object. ``response`` is the ``HttpResponse``
  167. object returned by a Django view.
  168. ``process_response()`` should return an ``HttpResponse`` object. It could alter
  169. the given ``response``, or it could create and return a brand-new
  170. ``HttpResponse``.
  171. ``process_exception``
  172. ---------------------
  173. Interface: ``process_exception(self, request, exception)``
  174. ``request`` is an ``HttpRequest`` object. ``exception`` is an ``Exception``
  175. object raised by the view function.
  176. Django calls ``process_exception()`` when a view raises an exception.
  177. ``process_exception()`` should return either ``None`` or an ``HttpResponse``
  178. object. If it returns an ``HttpResponse`` object, the response will be returned
  179. to the browser. Otherwise, default exception handling kicks in.
  180. ``__init__``
  181. ------------
  182. Most middleware classes won't need an initializer since middleware classes are
  183. essentially placeholders for the ``process_*`` methods. If you do need some
  184. global state you may use ``__init__`` to set up. However, keep in mind a couple
  185. of caveats:
  186. * Django initializes your middleware without any arguments, so you can't
  187. define ``__init__`` as requiring any arguments.
  188. * Unlike the ``process_*`` methods which get called once per request,
  189. ``__init__`` gets called only *once*, when the web server starts up.
  190. Marking middleware as unused
  191. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  192. It's sometimes useful to determine at run-time whether a piece of middleware
  193. should be used. In these cases, your middleware's ``__init__`` method may raise
  194. ``django.core.exceptions.MiddlewareNotUsed``. Django will then remove that piece
  195. of middleware from the middleware process.
  196. Guidelines
  197. ----------
  198. * Middleware classes don't have to subclass anything.
  199. * The middleware class can live anywhere on your Python path. All Django
  200. cares about is that the ``MIDDLEWARE_CLASSES`` setting includes the path
  201. to it.
  202. * Feel free to look at Django's available middleware for examples. The
  203. core Django middleware classes are in ``django/middleware/`` in the
  204. Django distribution. The session middleware is in
  205. ``django/contrib/sessions``.
  206. * If you write a middleware component that you think would be useful to
  207. other people, contribute to the community! Let us know, and we'll
  208. consider adding it to Django.