middleware.txt 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 how middleware works, how you activate middleware, and
  11. how to write your own middleware. Django ships with some built-in middleware
  12. you can use right out of the box; they're documented in the :doc:`built-in
  13. middleware reference </ref/middleware>`.
  14. Activating middleware
  15. =====================
  16. To activate a middleware component, add it to the :setting:`MIDDLEWARE_CLASSES`
  17. list in your Django settings. In :setting:`MIDDLEWARE_CLASSES`, each middleware
  18. component is represented by a string: the full Python path to the middleware's
  19. class name. For example, here's the default :setting:`MIDDLEWARE_CLASSES`
  20. created by :djadmin:`django-admin.py startproject <startproject>`::
  21. MIDDLEWARE_CLASSES = (
  22. 'django.middleware.common.CommonMiddleware',
  23. 'django.contrib.sessions.middleware.SessionMiddleware',
  24. 'django.middleware.csrf.CsrfViewMiddleware',
  25. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  26. 'django.contrib.messages.middleware.MessageMiddleware',
  27. )
  28. During the request phases (:meth:`process_request` and :meth:`process_view`),
  29. Django applies middleware in the order it's defined in
  30. :setting:`MIDDLEWARE_CLASSES`, top-down. During the response phases
  31. (:meth:`process_template_response`, :meth:`process_response`, and
  32. :meth:`process_exception`), the classes are applied in reverse order, from the
  33. bottom up.
  34. .. image:: _images/middleware.svg
  35. :alt: middleware application order
  36. :width: 480
  37. :height: 408
  38. If you prefer, you can also think of it like an onion: each middleware class
  39. is a "layer" that wraps the view.
  40. A Django installation doesn't require any middleware -- e.g.,
  41. :setting:`MIDDLEWARE_CLASSES` can be empty, if you'd like -- but it's strongly
  42. suggested that you at least use
  43. :class:`~django.middleware.common.CommonMiddleware`.
  44. Writing your own middleware
  45. ===========================
  46. Writing your own middleware is easy. Each middleware component is a single
  47. Python class that defines one or more of the following methods:
  48. .. _request-middleware:
  49. ``process_request``
  50. -------------------
  51. .. method:: process_request(self, request)
  52. ``request`` is an :class:`~django.http.HttpRequest` object. This method is
  53. called on each request, before Django decides which view to execute.
  54. ``process_request()`` should return either ``None`` or an
  55. :class:`~django.http.HttpResponse` object. If it returns ``None``, Django will
  56. continue processing this request, executing any other middleware and, then, the
  57. appropriate view. If it returns an :class:`~django.http.HttpResponse` object,
  58. Django won't bother calling ANY other request, view or exception middleware, or
  59. the appropriate view; it'll return that :class:`~django.http.HttpResponse`.
  60. Response middleware is always called on every response.
  61. .. _view-middleware:
  62. ``process_view``
  63. ----------------
  64. .. method:: process_view(self, request, view_func, view_args, view_kwargs)
  65. ``request`` is an :class:`~django.http.HttpRequest` object. ``view_func`` is
  66. the Python function that Django is about to use. (It's the actual function
  67. object, not the name of the function as a string.) ``view_args`` is a list of
  68. positional arguments that will be passed to the view, and ``view_kwargs`` is a
  69. dictionary of keyword arguments that will be passed to the view. Neither
  70. ``view_args`` nor ``view_kwargs`` include the first view argument
  71. (``request``).
  72. ``process_view()`` is called just before Django calls the view. It should
  73. return either ``None`` or an :class:`~django.http.HttpResponse` object. If it
  74. returns ``None``, Django will continue processing this request, executing any
  75. other ``process_view()`` middleware and, then, the appropriate view. If it
  76. returns an :class:`~django.http.HttpResponse` object, Django won't bother
  77. calling ANY other request, view or exception middleware, or the appropriate
  78. view; it'll return that :class:`~django.http.HttpResponse`. Response
  79. middleware is always called on every response.
  80. .. note::
  81. Accessing :attr:`request.POST <django.http.HttpRequest.POST>` or
  82. :attr:`request.REQUEST <django.http.HttpRequest.REQUEST>` inside middleware
  83. from ``process_request`` or ``process_view`` will prevent any view running
  84. after the middleware from being able to :ref:`modify the upload handlers
  85. for the request <modifying_upload_handlers_on_the_fly>`, and should
  86. normally be avoided.
  87. The :class:`~django.middleware.csrf.CsrfViewMiddleware` class can be
  88. considered an exception, as it provides the
  89. :func:`~django.views.decorators.csrf.csrf_exempt` and
  90. :func:`~django.views.decorators.csrf.csrf_protect` decorators which allow
  91. views to explicitly control at what point the CSRF validation should occur.
  92. .. _template-response-middleware:
  93. ``process_template_response``
  94. -----------------------------
  95. .. method:: process_template_response(self, request, response)
  96. ``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is a
  97. subclass of :class:`~django.template.response.SimpleTemplateResponse` (e.g.
  98. :class:`~django.template.response.TemplateResponse`) or any response object
  99. that implements a ``render`` method.
  100. ``process_template_response()`` must return a response object that implements a
  101. ``render`` method. It could alter the given ``response`` by changing
  102. ``response.template_name`` and ``response.context_data``, or it could create
  103. and return a brand-new
  104. :class:`~django.template.response.SimpleTemplateResponse` or equivalent.
  105. ``process_template_response()`` will only be called if the response
  106. instance has a ``render()`` method, indicating that it is a
  107. :class:`~django.template.response.TemplateResponse` or equivalent.
  108. You don't need to explicitly render responses -- responses will be
  109. automatically rendered once all template response middleware has been
  110. called.
  111. Middleware are run in reverse order during the response phase, which
  112. includes process_template_response.
  113. .. _response-middleware:
  114. ``process_response``
  115. --------------------
  116. .. method:: process_response(self, request, response)
  117. ``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is the
  118. :class:`~django.http.HttpResponse` object returned by a Django view.
  119. ``process_response()`` must return an :class:`~django.http.HttpResponse`
  120. object. It could alter the given ``response``, or it could create and return a
  121. brand-new :class:`~django.http.HttpResponse`.
  122. Unlike the ``process_request()`` and ``process_view()`` methods, the
  123. ``process_response()`` method is always called, even if the ``process_request()``
  124. and ``process_view()`` methods of the same middleware class were skipped because
  125. an earlier middleware method returned an :class:`~django.http.HttpResponse`
  126. (this means that your ``process_response()`` method cannot rely on setup done in
  127. ``process_request()``, for example). In addition, during the response phase the
  128. classes are applied in reverse order, from the bottom up. This means classes
  129. defined at the end of :setting:`MIDDLEWARE_CLASSES` will be run first.
  130. .. versionchanged:: 1.5
  131. ``response`` may also be an :class:`~django.http.StreamingHttpResponse`
  132. object.
  133. Unlike :class:`~django.http.HttpResponse`,
  134. :class:`~django.http.StreamingHttpResponse` does not have a ``content``
  135. attribute. As a result, middleware can no longer assume that all responses
  136. will have a ``content`` attribute. If they need access to the content, they
  137. must test for streaming responses and adjust their behavior accordingly::
  138. if response.streaming:
  139. response.streaming_content = wrap_streaming_content(response.streaming_content)
  140. else:
  141. response.content = wrap_content(response.content)
  142. ``streaming_content`` should be assumed to be too large to hold in memory.
  143. Middleware may wrap it in a new generator, but must not consume it.
  144. .. _exception-middleware:
  145. ``process_exception``
  146. ---------------------
  147. .. method:: process_exception(self, request, exception)
  148. ``request`` is an :class:`~django.http.HttpRequest` object. ``exception`` is an
  149. ``Exception`` object raised by the view function.
  150. Django calls ``process_exception()`` when a view raises an exception.
  151. ``process_exception()`` should return either ``None`` or an
  152. :class:`~django.http.HttpResponse` object. If it returns an
  153. :class:`~django.http.HttpResponse` object, the response will be returned to
  154. the browser. Otherwise, default exception handling kicks in.
  155. Again, middleware are run in reverse order during the response phase, which
  156. includes ``process_exception``. If an exception middleware returns a response,
  157. the middleware classes above that middleware will not be called at all.
  158. ``__init__``
  159. ------------
  160. Most middleware classes won't need an initializer since middleware classes are
  161. essentially placeholders for the ``process_*`` methods. If you do need some
  162. global state you may use ``__init__`` to set up. However, keep in mind a couple
  163. of caveats:
  164. * Django initializes your middleware without any arguments, so you can't
  165. define ``__init__`` as requiring any arguments.
  166. * Unlike the ``process_*`` methods which get called once per request,
  167. ``__init__`` gets called only *once*, when the Web server responds to the
  168. first request.
  169. Marking middleware as unused
  170. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  171. It's sometimes useful to determine at run-time whether a piece of middleware
  172. should be used. In these cases, your middleware's ``__init__`` method may raise
  173. ``django.core.exceptions.MiddlewareNotUsed``. Django will then remove that
  174. piece of middleware from the middleware process.
  175. Guidelines
  176. ----------
  177. * Middleware classes don't have to subclass anything.
  178. * The middleware class can live anywhere on your Python path. All Django
  179. cares about is that the :setting:`MIDDLEWARE_CLASSES` setting includes
  180. the path to it.
  181. * Feel free to look at :doc:`Django's available middleware
  182. </ref/middleware>` for examples.
  183. * If you write a middleware component that you think would be useful to
  184. other people, contribute to the community! :doc:`Let us know
  185. </internals/contributing/index>`, and we'll consider adding it to Django.