middleware.txt 16 KB

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