middleware.txt 11 KB

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