middleware.txt 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. .. _topics-http-middleware:
  2. ==========
  3. Middleware
  4. ==========
  5. Middleware is a framework of hooks into Django's request/response processing.
  6. It's a light, low-level "plugin" system for globally altering Django's input
  7. and/or output.
  8. Each middleware component is responsible for doing some specific function. For
  9. example, Django includes a middleware component, ``XViewMiddleware``, that adds
  10. an ``"X-View"`` HTTP header to every response to a ``HEAD`` request.
  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 :ref:`built-in
  14. middleware reference <ref-middleware>`.
  15. Activating middleware
  16. =====================
  17. To activate a middleware component, add it to the :setting:`MIDDLEWARE_CLASSES`
  18. list in your Django settings. In :setting:`MIDDLEWARE_CLASSES`, each middleware
  19. component is represented by a string: the full Python path to the middleware's
  20. class name. For example, here's the default :setting:`MIDDLEWARE_CLASSES`
  21. created by :djadmin:`django-admin.py startproject <startproject>`::
  22. MIDDLEWARE_CLASSES = (
  23. 'django.middleware.common.CommonMiddleware',
  24. 'django.contrib.sessions.middleware.SessionMiddleware',
  25. 'django.middleware.csrf.CsrfViewMiddleware',
  26. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  27. 'django.contrib.messages.middleware.MessageMiddleware',
  28. )
  29. During the request phases (:meth:`process_request` and :meth:`process_view`
  30. middleware), Django applies middleware in the order it's defined in
  31. :setting:`MIDDLEWARE_CLASSES`, top-down. During the response phases
  32. (:meth:`process_response` and :meth:`process_exception` middleware), the
  33. classes are applied in reverse order, from the bottom up. You can think of it
  34. like an onion: each middleware class is a "layer" that wraps the view:
  35. .. image:: _images/middleware.png
  36. :width: 502
  37. :height: 417
  38. :alt: Middleware application order.
  39. A Django installation doesn't require any middleware -- e.g.,
  40. :setting:`MIDDLEWARE_CLASSES` can be empty, if you'd like -- but it's strongly
  41. suggested that you at least use
  42. :class:`~django.middleware.common.CommonMiddleware`.
  43. Writing your own middleware
  44. ===========================
  45. Writing your own middleware is easy. Each middleware component is a single
  46. Python class that defines one or more of the following methods:
  47. .. _request-middleware:
  48. ``process_request``
  49. -------------------
  50. .. method:: process_request(self, request)
  51. ``request`` is an :class:`~django.http.HttpRequest` object. This method is
  52. called on each request, before Django decides which view to execute.
  53. ``process_request()`` should return either ``None`` or an
  54. :class:`~django.http.HttpResponse` object. If it returns ``None``, Django will
  55. continue processing this request, executing any other middleware and, then, the
  56. appropriate view. If it returns an :class:`~django.http.HttpResponse` object,
  57. Django won't bother calling ANY other request, view or exception middleware, or
  58. the appropriate view; it'll return that :class:`~django.http.HttpResponse`.
  59. Response middleware is always called on every response.
  60. .. _view-middleware:
  61. ``process_view``
  62. ----------------
  63. .. method:: process_view(self, request, view_func, view_args, view_kwargs)
  64. ``request`` is an :class:`~django.http.HttpRequest` object. ``view_func`` is
  65. the Python function that Django is about to use. (It's the actual function
  66. object, not the name of the function as a string.) ``view_args`` is a list of
  67. positional arguments that will be passed to the view, and ``view_kwargs`` is a
  68. dictionary of keyword arguments that will be passed to the view. Neither
  69. ``view_args`` nor ``view_kwargs`` include the first view argument
  70. (``request``).
  71. ``process_view()`` is called just before Django calls the view. It should
  72. return either ``None`` or an :class:`~django.http. HttpResponse` object. If it
  73. returns ``None``, Django will continue processing this request, executing any
  74. other ``process_view()`` middleware and, then, the appropriate view. If it
  75. returns an :class:`~django.http. HttpResponse` object, Django won't bother
  76. calling ANY other request, view or exception middleware, or the appropriate
  77. view; it'll return that :class:`~django.http. HttpResponse`. Response
  78. middleware is always called on every response.
  79. .. _response-middleware:
  80. ``process_response``
  81. --------------------
  82. .. method:: process_response(self, request, response)
  83. ``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is the
  84. :class:`~django.http. HttpResponse` object returned by a Django view.
  85. ``process_response()`` must return an :class:`~django.http. HttpResponse`
  86. object. It could alter the given ``response``, or it could create and return a
  87. brand-new :class:`~django.http. HttpResponse`.
  88. Unlike the ``process_request()`` and ``process_view()`` methods, the
  89. ``process_response()`` method is always called, even if the ``process_request()``
  90. and ``process_view()`` methods of the same middleware class were skipped because
  91. an earlier middleware method returned an :class:`~django.http. HttpResponse`
  92. (this means that your ``process_response()`` method cannot rely on setup done in
  93. ``process_request()``, for example). In addition, during the response phase the
  94. classes are applied in reverse order, from the bottom up. This means classes
  95. defined at the end of :setting:`MIDDLEWARE_CLASSES` will be run first.
  96. .. _exception-middleware:
  97. ``process_exception``
  98. ---------------------
  99. .. method:: process_exception(self, request, exception)
  100. ``request`` is an :class:`~django.http.HttpRequest` object. ``exception`` is an
  101. ``Exception`` object raised by the view function.
  102. Django calls ``process_exception()`` when a view raises an exception.
  103. ``process_exception()`` should return either ``None`` or an
  104. :class:`~django.http. HttpResponse` object. If it returns an
  105. :class:`~django.http. HttpResponse` object, the response will be returned to
  106. the browser. Otherwise, default exception handling kicks in.
  107. Again, middleware are run in reverse order during the response phase, which
  108. includes ``process_exception``. If an exception middleware return a response,
  109. the middleware classes above that middleware will not be called at all.
  110. ``__init__``
  111. ------------
  112. Most middleware classes won't need an initializer since middleware classes are
  113. essentially placeholders for the ``process_*`` methods. If you do need some
  114. global state you may use ``__init__`` to set up. However, keep in mind a couple
  115. of caveats:
  116. * Django initializes your middleware without any arguments, so you can't
  117. define ``__init__`` as requiring any arguments.
  118. * Unlike the ``process_*`` methods which get called once per request,
  119. ``__init__`` gets called only *once*, when the web server starts up.
  120. Marking middleware as unused
  121. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  122. It's sometimes useful to determine at run-time whether a piece of middleware
  123. should be used. In these cases, your middleware's ``__init__`` method may raise
  124. ``django.core.exceptions.MiddlewareNotUsed``. Django will then remove that
  125. piece of middleware from the middleware process.
  126. Guidelines
  127. ----------
  128. * Middleware classes don't have to subclass anything.
  129. * The middleware class can live anywhere on your Python path. All Django
  130. cares about is that the :setting:`MIDDLEWARE_CLASSES` setting includes
  131. the path to it.
  132. * Feel free to look at :ref:`Django's available middleware
  133. <ref-middleware>` for examples.
  134. * If you write a middleware component that you think would be useful to
  135. other people, contribute to the community! :ref:`Let us know
  136. <internals-contributing>`, and we'll consider adding it to Django.