middleware.txt 15 KB

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