middleware.txt 11 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. or output.
  7. Each middleware component is responsible for doing some specific function. For
  8. example, Django includes a middleware component,
  9. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`, that
  10. associates users with requests using sessions.
  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`. See
  40. :ref:`middleware-ordering` for some common hints about ordering of Django
  41. middleware classes.
  42. Hooks and application order
  43. ===========================
  44. During the request phase, before calling the view, Django applies middleware
  45. in the order it's defined in :setting:`MIDDLEWARE_CLASSES`, top-down. Two
  46. hooks are available:
  47. * :meth:`process_request`
  48. * :meth:`process_view`
  49. During the response phase, after calling the view, middleware are applied in
  50. reverse order, from the bottom up. Three hooks are available:
  51. * :meth:`process_exception` (only if the view raised an exception)
  52. * :meth:`process_template_response` (only for template responses)
  53. * :meth:`process_response`
  54. .. image:: _images/middleware.*
  55. :alt: middleware application order
  56. :width: 481
  57. :height: 409
  58. If you prefer, you can also think of it like an onion: each middleware class
  59. is a "layer" that wraps the view.
  60. The behavior of each hook is described below.
  61. Writing your own middleware
  62. ===========================
  63. Writing your own middleware is easy. Each middleware component is a single
  64. Python class that defines one or more of the following methods:
  65. .. _request-middleware:
  66. ``process_request``
  67. -------------------
  68. .. method:: process_request(request)
  69. ``request`` is an :class:`~django.http.HttpRequest` object.
  70. ``process_request()`` is called on each request, before Django decides which
  71. view to execute.
  72. It should return either ``None`` or an :class:`~django.http.HttpResponse`
  73. object. If it returns ``None``, Django will continue processing this request,
  74. executing any other ``process_request()`` middleware, then, ``process_view()``
  75. middleware, and finally, the appropriate view. If it returns an
  76. :class:`~django.http.HttpResponse` object, Django won't bother calling any
  77. other request, view or exception middleware, or the appropriate view; it'll
  78. apply response middleware to that :class:`~django.http.HttpResponse`, and
  79. return the result.
  80. .. _view-middleware:
  81. ``process_view``
  82. ----------------
  83. .. method:: process_view(request, view_func, view_args, view_kwargs)
  84. ``request`` is an :class:`~django.http.HttpRequest` object. ``view_func`` is
  85. the Python function that Django is about to use. (It's the actual function
  86. object, not the name of the function as a string.) ``view_args`` is a list of
  87. positional arguments that will be passed to the view, and ``view_kwargs`` is a
  88. dictionary of keyword arguments that will be passed to the view. Neither
  89. ``view_args`` nor ``view_kwargs`` include the first view argument
  90. (``request``).
  91. ``process_view()`` is called just before Django calls the view.
  92. It should return either ``None`` or an :class:`~django.http.HttpResponse`
  93. object. If it returns ``None``, Django will continue processing this request,
  94. executing any other ``process_view()`` middleware and, then, the appropriate
  95. view. If it returns an :class:`~django.http.HttpResponse` object, Django won't
  96. bother calling any other view or exception middleware, or the appropriate
  97. view; it'll apply response middleware to that
  98. :class:`~django.http.HttpResponse`, and return the result.
  99. .. note::
  100. Accessing :attr:`request.POST <django.http.HttpRequest.POST>` or
  101. :attr:`request.REQUEST <django.http.HttpRequest.REQUEST>` inside middleware
  102. from ``process_request`` or ``process_view`` will prevent any view running
  103. after the middleware from being able to :ref:`modify the upload handlers
  104. for the request <modifying_upload_handlers_on_the_fly>`, and should
  105. normally be avoided.
  106. The :class:`~django.middleware.csrf.CsrfViewMiddleware` class can be
  107. considered an exception, as it provides the
  108. :func:`~django.views.decorators.csrf.csrf_exempt` and
  109. :func:`~django.views.decorators.csrf.csrf_protect` decorators which allow
  110. views to explicitly control at what point the CSRF validation should occur.
  111. .. _template-response-middleware:
  112. ``process_template_response``
  113. -----------------------------
  114. .. method:: process_template_response(request, response)
  115. ``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is
  116. the :class:`~django.template.response.TemplateResponse` object (or equivalent)
  117. returned by a Django view or by a middleware.
  118. ``process_template_response()`` is called just after the view has finished
  119. executing, if the response instance has a ``render()`` method, indicating that
  120. it is a :class:`~django.template.response.TemplateResponse` or equivalent.
  121. It must return a response object that implements a ``render`` method. It could
  122. alter the given ``response`` by changing ``response.template_name`` and
  123. ``response.context_data``, or it could create and return a brand-new
  124. :class:`~django.template.response.TemplateResponse` or equivalent.
  125. You don't need to explicitly render responses -- responses will be
  126. automatically rendered once all template response middleware has been
  127. called.
  128. Middleware are run in reverse order during the response phase, which
  129. includes ``process_template_response()``.
  130. .. _response-middleware:
  131. ``process_response``
  132. --------------------
  133. .. method:: process_response(request, response)
  134. ``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is
  135. the :class:`~django.http.HttpResponse` or
  136. :class:`~django.http.StreamingHttpResponse` object returned by a Django view
  137. or by a middleware.
  138. ``process_response()`` is called on all responses before they're returned to
  139. the browser.
  140. It must return an :class:`~django.http.HttpResponse` or
  141. :class:`~django.http.StreamingHttpResponse` object. It could alter the given
  142. ``response``, or it could create and return a brand-new
  143. :class:`~django.http.HttpResponse` or
  144. :class:`~django.http.StreamingHttpResponse`.
  145. Unlike the ``process_request()`` and ``process_view()`` methods, the
  146. ``process_response()`` method is always called, even if the
  147. ``process_request()`` and ``process_view()`` methods of the same middleware
  148. class were skipped (because an earlier middleware method returned an
  149. :class:`~django.http.HttpResponse`). In particular, this means that your
  150. ``process_response()`` method cannot rely on setup done in
  151. ``process_request()``.
  152. Finally, remember that during the response phase, middleware are applied in
  153. reverse order, from the bottom up. This means classes defined at the end of
  154. :setting:`MIDDLEWARE_CLASSES` will be run first.
  155. Dealing with streaming responses
  156. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  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(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.