middleware.txt 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. )
  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. .. _response-middleware:
  79. ``process_response``
  80. --------------------
  81. .. method:: process_response(self, request, response)
  82. ``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is the
  83. :class:`~django.http. HttpResponse` object returned by a Django view.
  84. ``process_response()`` must return an :class:`~django.http. HttpResponse`
  85. object. It could alter the given ``response``, or it could create and return a
  86. brand-new :class:`~django.http. HttpResponse`.
  87. Unlike the ``process_request()`` and ``process_view()`` methods, the
  88. ``process_response()`` method is always called, even if the ``process_request()``
  89. and ``process_view()`` methods of the same middleware class were skipped because
  90. an earlier middleware method returned an :class:`~django.http. HttpResponse`
  91. (this means that your ``process_response()`` method cannot rely on setup done in
  92. ``process_request()``, for example). In addition, during the response phase the
  93. classes are applied in reverse order, from the bottom up. This means classes
  94. defined at the end of :setting:`MIDDLEWARE_CLASSES` will be run first.
  95. .. _exception-middleware:
  96. ``process_exception``
  97. ---------------------
  98. .. method:: process_exception(self, request, exception)
  99. ``request`` is an :class:`~django.http.HttpRequest` object. ``exception`` is an
  100. ``Exception`` object raised by the view function.
  101. Django calls ``process_exception()`` when a view raises an exception.
  102. ``process_exception()`` should return either ``None`` or an
  103. :class:`~django.http. HttpResponse` object. If it returns an
  104. :class:`~django.http. HttpResponse` object, the response will be returned to
  105. the browser. Otherwise, default exception handling kicks in.
  106. Again, middleware are run in reverse order during the response phase, which
  107. includes ``process_exception``. If an exception middleware return a response,
  108. the middleware classes above that middleware will not be called at all.
  109. ``__init__``
  110. ------------
  111. Most middleware classes won't need an initializer since middleware classes are
  112. essentially placeholders for the ``process_*`` methods. If you do need some
  113. global state you may use ``__init__`` to set up. However, keep in mind a couple
  114. of caveats:
  115. * Django initializes your middleware without any arguments, so you can't
  116. define ``__init__`` as requiring any arguments.
  117. * Unlike the ``process_*`` methods which get called once per request,
  118. ``__init__`` gets called only *once*, when the web server starts up.
  119. Marking middleware as unused
  120. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  121. It's sometimes useful to determine at run-time whether a piece of middleware
  122. should be used. In these cases, your middleware's ``__init__`` method may raise
  123. ``django.core.exceptions.MiddlewareNotUsed``. Django will then remove that
  124. piece of middleware from the middleware process.
  125. Guidelines
  126. ----------
  127. * Middleware classes don't have to subclass anything.
  128. * The middleware class can live anywhere on your Python path. All Django
  129. cares about is that the :setting:`MIDDLEWARE_CLASSES` setting includes
  130. the path to it.
  131. * Feel free to look at :ref:`Django's available middleware
  132. <ref-middleware>` for examples.
  133. * If you write a middleware component that you think would be useful to
  134. other people, contribute to the community! :ref:`Let us know
  135. <internals-contributing>`, and we'll consider adding it to Django.