middleware.txt 9.5 KB

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