middleware.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. Writing your own middleware
  16. ===========================
  17. A middleware factory is a callable that takes a ``get_response`` callable and
  18. returns a middleware. A middleware is a callable that takes a request and
  19. returns a response, just like a view.
  20. A middleware can be written as a function that looks like this::
  21. def simple_middleware(get_response):
  22. # One-time configuration and initialization.
  23. def middleware(request):
  24. # Code to be executed for each request before
  25. # the view (and later middleware) are called.
  26. response = get_response(request)
  27. # Code to be executed for each request/response after
  28. # the view is called.
  29. return response
  30. return middleware
  31. Or it can be written as a class whose instances are callable, like this::
  32. class SimpleMiddleware:
  33. def __init__(self, get_response):
  34. self.get_response = get_response
  35. # One-time configuration and initialization.
  36. def __call__(self, request):
  37. # Code to be executed for each request before
  38. # the view (and later middleware) are called.
  39. response = self.get_response(request)
  40. # Code to be executed for each request/response after
  41. # the view is called.
  42. return response
  43. The ``get_response`` callable provided by Django might be the actual view (if
  44. this is the last listed middleware) or it might be the next middleware in the
  45. chain. The current middleware doesn't need to know or care what exactly it is,
  46. just that it represents whatever comes next.
  47. The above is a slight simplification -- the ``get_response`` callable for the
  48. last middleware in the chain won't be the actual view but rather a wrapper
  49. method from the handler which takes care of applying :ref:`view middleware
  50. <view-middleware>`, calling the view with appropriate URL arguments, and
  51. applying :ref:`template-response <template-response-middleware>` and
  52. :ref:`exception <exception-middleware>` middleware.
  53. Middleware can live anywhere on your Python path.
  54. ``__init__(get_response)``
  55. --------------------------
  56. Middleware factories must accept a ``get_response`` argument. You can also
  57. initialize some global state for the middleware. Keep in mind a couple of
  58. caveats:
  59. * Django initializes your middleware with only the ``get_response`` argument,
  60. so you can't define ``__init__()`` as requiring any other arguments.
  61. * Unlike the ``__call__()`` method which is called once per request,
  62. ``__init__()`` is called only *once*, when the Web server starts.
  63. Marking middleware as unused
  64. ----------------------------
  65. It's sometimes useful to determine at startup time whether a piece of
  66. middleware should be used. In these cases, your middleware's ``__init__()``
  67. method may raise :exc:`~django.core.exceptions.MiddlewareNotUsed`. Django will
  68. then remove that middleware from the middleware process and log a debug message
  69. to the :ref:`django-request-logger` logger when :setting:`DEBUG` is ``True``.
  70. Activating middleware
  71. =====================
  72. To activate a middleware component, add it to the :setting:`MIDDLEWARE` list in
  73. your Django settings.
  74. In :setting:`MIDDLEWARE`, each middleware component is represented by a string:
  75. the full Python path to the middleware factory's class or function name. For
  76. example, here's the default value created by :djadmin:`django-admin
  77. startproject <startproject>`::
  78. MIDDLEWARE = [
  79. 'django.middleware.security.SecurityMiddleware',
  80. 'django.contrib.sessions.middleware.SessionMiddleware',
  81. 'django.middleware.common.CommonMiddleware',
  82. 'django.middleware.csrf.CsrfViewMiddleware',
  83. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  84. 'django.contrib.messages.middleware.MessageMiddleware',
  85. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  86. ]
  87. A Django installation doesn't require any middleware — :setting:`MIDDLEWARE`
  88. can be empty, if you'd like — but it's strongly suggested that you at least use
  89. :class:`~django.middleware.common.CommonMiddleware`.
  90. The order in :setting:`MIDDLEWARE` matters because a middleware can depend on
  91. other middleware. For instance,
  92. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware` stores the
  93. authenticated user in the session; therefore, it must run after
  94. :class:`~django.contrib.sessions.middleware.SessionMiddleware`. See
  95. :ref:`middleware-ordering` for some common hints about ordering of Django
  96. middleware classes.
  97. Middleware order and layering
  98. =============================
  99. During the request phase, before calling the view, Django applies middleware in
  100. the order it's defined in :setting:`MIDDLEWARE`, top-down.
  101. You can think of it like an onion: each middleware class is a "layer" that
  102. wraps the view, which is in the core of the onion. If the request passes
  103. through all the layers of the onion (each one calls ``get_response`` to pass
  104. the request in to the next layer), all the way to the view at the core, the
  105. response will then pass through every layer (in reverse order) on the way back
  106. out.
  107. If one of the layers decides to short-circuit and return a response without
  108. ever calling its ``get_response``, none of the layers of the onion inside that
  109. layer (including the view) will see the request or the response. The response
  110. will only return through the same layers that the request passed in through.
  111. Other middleware hooks
  112. ======================
  113. Besides the basic request/response middleware pattern described earlier, you
  114. can add three other special methods to class-based middleware:
  115. .. _view-middleware:
  116. ``process_view()``
  117. ------------------
  118. .. method:: process_view(request, view_func, view_args, view_kwargs)
  119. ``request`` is an :class:`~django.http.HttpRequest` object. ``view_func`` is
  120. the Python function that Django is about to use. (It's the actual function
  121. object, not the name of the function as a string.) ``view_args`` is a list of
  122. positional arguments that will be passed to the view, and ``view_kwargs`` is a
  123. dictionary of keyword arguments that will be passed to the view. Neither
  124. ``view_args`` nor ``view_kwargs`` include the first view argument
  125. (``request``).
  126. ``process_view()`` is called just before Django calls the view.
  127. It should return either ``None`` or an :class:`~django.http.HttpResponse`
  128. object. If it returns ``None``, Django will continue processing this request,
  129. executing any other ``process_view()`` middleware and, then, the appropriate
  130. view. If it returns an :class:`~django.http.HttpResponse` object, Django won't
  131. bother calling the appropriate view; it'll apply response middleware to that
  132. :class:`~django.http.HttpResponse` and return the result.
  133. .. note::
  134. Accessing :attr:`request.POST <django.http.HttpRequest.POST>` inside
  135. middleware before the view runs or in ``process_view()`` will prevent any
  136. view running after the middleware from being able to :ref:`modify the
  137. upload handlers for the request <modifying_upload_handlers_on_the_fly>`,
  138. and should normally be avoided.
  139. The :class:`~django.middleware.csrf.CsrfViewMiddleware` class can be
  140. considered an exception, as it provides the
  141. :func:`~django.views.decorators.csrf.csrf_exempt` and
  142. :func:`~django.views.decorators.csrf.csrf_protect` decorators which allow
  143. views to explicitly control at what point the CSRF validation should occur.
  144. .. _exception-middleware:
  145. ``process_exception()``
  146. -----------------------
  147. .. method:: process_exception(request, exception)
  148. ``request`` is an :class:`~django.http.HttpRequest` object. ``exception`` is an
  149. ``Exception`` object raised by the view function.
  150. Django calls ``process_exception()`` when a view raises an exception.
  151. ``process_exception()`` should return either ``None`` or an
  152. :class:`~django.http.HttpResponse` object. If it returns an
  153. :class:`~django.http.HttpResponse` object, the template response and response
  154. middleware will be applied and the resulting response returned to the
  155. browser. Otherwise, :ref:`default exception handling <error-views>` kicks in.
  156. Again, middleware are run in reverse order during the response phase, which
  157. includes ``process_exception``. If an exception middleware returns a response,
  158. the ``process_exception`` methods of the middleware classes above that
  159. middleware won't be called at all.
  160. .. _template-response-middleware:
  161. ``process_template_response()``
  162. -------------------------------
  163. .. method:: process_template_response(request, response)
  164. ``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is
  165. the :class:`~django.template.response.TemplateResponse` object (or equivalent)
  166. returned by a Django view or by a middleware.
  167. ``process_template_response()`` is called just after the view has finished
  168. executing, if the response instance has a ``render()`` method, indicating that
  169. it is a :class:`~django.template.response.TemplateResponse` or equivalent.
  170. It must return a response object that implements a ``render`` method. It could
  171. alter the given ``response`` by changing ``response.template_name`` and
  172. ``response.context_data``, or it could create and return a brand-new
  173. :class:`~django.template.response.TemplateResponse` or equivalent.
  174. You don't need to explicitly render responses -- responses will be
  175. automatically rendered once all template response middleware has been
  176. called.
  177. Middleware are run in reverse order during the response phase, which
  178. includes ``process_template_response()``.
  179. Dealing with streaming responses
  180. ================================
  181. Unlike :class:`~django.http.HttpResponse`,
  182. :class:`~django.http.StreamingHttpResponse` does not have a ``content``
  183. attribute. As a result, middleware can no longer assume that all responses
  184. will have a ``content`` attribute. If they need access to the content, they
  185. must test for streaming responses and adjust their behavior accordingly::
  186. if response.streaming:
  187. response.streaming_content = wrap_streaming_content(response.streaming_content)
  188. else:
  189. response.content = alter_content(response.content)
  190. .. note::
  191. ``streaming_content`` should be assumed to be too large to hold in memory.
  192. Response middleware may wrap it in a new generator, but must not consume
  193. it. Wrapping is typically implemented as follows::
  194. def wrap_streaming_content(content):
  195. for chunk in content:
  196. yield alter_content(chunk)
  197. Exception handling
  198. ==================
  199. Django automatically converts exceptions raised by the view or by middleware
  200. into an appropriate HTTP response with an error status code. :ref:`Certain
  201. exceptions <error-views>` are converted to 4xx status codes, while an unknown
  202. exception is converted to a 500 status code.
  203. This conversion takes place before and after each middleware (you can think of
  204. it as the thin film in between each layer of the onion), so that every
  205. middleware can always rely on getting some kind of HTTP response back from
  206. calling its ``get_response`` callable. Middleware don't need to worry about
  207. wrapping their call to ``get_response`` in a ``try/except`` and handling an
  208. exception that might have been raised by a later middleware or the view. Even
  209. if the very next middleware in the chain raises an
  210. :class:`~django.http.Http404` exception, for example, your middleware won't see
  211. that exception; instead it will get an :class:`~django.http.HttpResponse`
  212. object with a :attr:`~django.http.HttpResponse.status_code` of 404.
  213. .. _upgrading-middleware:
  214. Upgrading pre-Django 1.10-style middleware
  215. ==========================================
  216. .. class:: django.utils.deprecation.MiddlewareMixin
  217. :module:
  218. Django provides ``django.utils.deprecation.MiddlewareMixin`` to ease creating
  219. middleware classes that are compatible with both :setting:`MIDDLEWARE` and the
  220. old ``MIDDLEWARE_CLASSES``. All middleware classes included with Django
  221. are compatible with both settings.
  222. The mixin provides an ``__init__()`` method that accepts an optional
  223. ``get_response`` argument and stores it in ``self.get_response``.
  224. The ``__call__()`` method:
  225. #. Calls ``self.process_request(request)`` (if defined).
  226. #. Calls ``self.get_response(request)`` to get the response from later
  227. middleware and the view.
  228. #. Calls ``self.process_response(request, response)`` (if defined).
  229. #. Returns the response.
  230. If used with ``MIDDLEWARE_CLASSES``, the ``__call__()`` method will
  231. never be used; Django calls ``process_request()`` and ``process_response()``
  232. directly.
  233. In most cases, inheriting from this mixin will be sufficient to make an
  234. old-style middleware compatible with the new system with sufficient
  235. backwards-compatibility. The new short-circuiting semantics will be harmless or
  236. even beneficial to the existing middleware. In a few cases, a middleware class
  237. may need some changes to adjust to the new semantics.
  238. These are the behavioral differences between using :setting:`MIDDLEWARE` and
  239. ``MIDDLEWARE_CLASSES``:
  240. #. Under ``MIDDLEWARE_CLASSES``, every middleware will always have its
  241. ``process_response`` method called, even if an earlier middleware
  242. short-circuited by returning a response from its ``process_request``
  243. method. Under :setting:`MIDDLEWARE`, middleware behaves more like an onion:
  244. the layers that a response goes through on the way out are the same layers
  245. that saw the request on the way in. If a middleware short-circuits, only
  246. that middleware and the ones before it in :setting:`MIDDLEWARE` will see the
  247. response.
  248. #. Under ``MIDDLEWARE_CLASSES``, ``process_exception`` is applied to
  249. exceptions raised from a middleware ``process_request`` method. Under
  250. :setting:`MIDDLEWARE`, ``process_exception`` applies only to exceptions
  251. raised from the view (or from the ``render`` method of a
  252. :class:`~django.template.response.TemplateResponse`). Exceptions raised from
  253. a middleware are converted to the appropriate HTTP response and then passed
  254. to the next middleware.
  255. #. Under ``MIDDLEWARE_CLASSES``, if a ``process_response`` method raises
  256. an exception, the ``process_response`` methods of all earlier middleware are
  257. skipped and a ``500 Internal Server Error`` HTTP response is always
  258. returned (even if the exception raised was e.g. an
  259. :class:`~django.http.Http404`). Under :setting:`MIDDLEWARE`, an exception
  260. raised from a middleware will immediately be converted to the appropriate
  261. HTTP response, and then the next middleware in line will see that
  262. response. Middleware are never skipped due to a middleware raising an
  263. exception.