middleware.txt 12 KB

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