middleware.txt 11 KB

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