middleware.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 either support only synchronous Python (the default), only
  54. asynchronous Python, or both. See :ref:`async-middleware` for details of how to
  55. advertise what you support, and know what kind of request you are getting.
  56. Middleware can live anywhere on your Python path.
  57. ``__init__(get_response)``
  58. --------------------------
  59. Middleware factories must accept a ``get_response`` argument. You can also
  60. initialize some global state for the middleware. Keep in mind a couple of
  61. caveats:
  62. * Django initializes your middleware with only the ``get_response`` argument,
  63. so you can't define ``__init__()`` as requiring any other arguments.
  64. * Unlike the ``__call__()`` method which is called once per request,
  65. ``__init__()`` is called only *once*, when the Web server starts.
  66. Marking middleware as unused
  67. ----------------------------
  68. It's sometimes useful to determine at startup time whether a piece of
  69. middleware should be used. In these cases, your middleware's ``__init__()``
  70. method may raise :exc:`~django.core.exceptions.MiddlewareNotUsed`. Django will
  71. then remove that middleware from the middleware process and log a debug message
  72. to the :ref:`django-request-logger` logger when :setting:`DEBUG` is ``True``.
  73. Activating middleware
  74. =====================
  75. To activate a middleware component, add it to the :setting:`MIDDLEWARE` list in
  76. your Django settings.
  77. In :setting:`MIDDLEWARE`, each middleware component is represented by a string:
  78. the full Python path to the middleware factory's class or function name. For
  79. example, here's the default value created by :djadmin:`django-admin
  80. startproject <startproject>`::
  81. MIDDLEWARE = [
  82. 'django.middleware.security.SecurityMiddleware',
  83. 'django.contrib.sessions.middleware.SessionMiddleware',
  84. 'django.middleware.common.CommonMiddleware',
  85. 'django.middleware.csrf.CsrfViewMiddleware',
  86. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  87. 'django.contrib.messages.middleware.MessageMiddleware',
  88. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  89. ]
  90. A Django installation doesn't require any middleware — :setting:`MIDDLEWARE`
  91. can be empty, if you'd like — but it's strongly suggested that you at least use
  92. :class:`~django.middleware.common.CommonMiddleware`.
  93. The order in :setting:`MIDDLEWARE` matters because a middleware can depend on
  94. other middleware. For instance,
  95. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware` stores the
  96. authenticated user in the session; therefore, it must run after
  97. :class:`~django.contrib.sessions.middleware.SessionMiddleware`. See
  98. :ref:`middleware-ordering` for some common hints about ordering of Django
  99. middleware classes.
  100. Middleware order and layering
  101. =============================
  102. During the request phase, before calling the view, Django applies middleware in
  103. the order it's defined in :setting:`MIDDLEWARE`, top-down.
  104. You can think of it like an onion: each middleware class is a "layer" that
  105. wraps the view, which is in the core of the onion. If the request passes
  106. through all the layers of the onion (each one calls ``get_response`` to pass
  107. the request in to the next layer), all the way to the view at the core, the
  108. response will then pass through every layer (in reverse order) on the way back
  109. out.
  110. If one of the layers decides to short-circuit and return a response without
  111. ever calling its ``get_response``, none of the layers of the onion inside that
  112. layer (including the view) will see the request or the response. The response
  113. will only return through the same layers that the request passed in through.
  114. Other middleware hooks
  115. ======================
  116. Besides the basic request/response middleware pattern described earlier, you
  117. can add three other special methods to class-based middleware:
  118. .. _view-middleware:
  119. ``process_view()``
  120. ------------------
  121. .. method:: process_view(request, view_func, view_args, view_kwargs)
  122. ``request`` is an :class:`~django.http.HttpRequest` object. ``view_func`` is
  123. the Python function that Django is about to use. (It's the actual function
  124. object, not the name of the function as a string.) ``view_args`` is a list of
  125. positional arguments that will be passed to the view, and ``view_kwargs`` is a
  126. dictionary of keyword arguments that will be passed to the view. Neither
  127. ``view_args`` nor ``view_kwargs`` include the first view argument
  128. (``request``).
  129. ``process_view()`` is called just before Django calls the view.
  130. It should return either ``None`` or an :class:`~django.http.HttpResponse`
  131. object. If it returns ``None``, Django will continue processing this request,
  132. executing any other ``process_view()`` middleware and, then, the appropriate
  133. view. If it returns an :class:`~django.http.HttpResponse` object, Django won't
  134. bother calling the appropriate view; it'll apply response middleware to that
  135. :class:`~django.http.HttpResponse` and return the result.
  136. .. note::
  137. Accessing :attr:`request.POST <django.http.HttpRequest.POST>` inside
  138. middleware before the view runs or in ``process_view()`` will prevent any
  139. view running after the middleware from being able to :ref:`modify the
  140. upload handlers for the request <modifying_upload_handlers_on_the_fly>`,
  141. and should normally be avoided.
  142. The :class:`~django.middleware.csrf.CsrfViewMiddleware` class can be
  143. considered an exception, as it provides the
  144. :func:`~django.views.decorators.csrf.csrf_exempt` and
  145. :func:`~django.views.decorators.csrf.csrf_protect` decorators which allow
  146. views to explicitly control at what point the CSRF validation should occur.
  147. .. _exception-middleware:
  148. ``process_exception()``
  149. -----------------------
  150. .. method:: process_exception(request, exception)
  151. ``request`` is an :class:`~django.http.HttpRequest` object. ``exception`` is an
  152. ``Exception`` object raised by the view function.
  153. Django calls ``process_exception()`` when a view raises an exception.
  154. ``process_exception()`` should return either ``None`` or an
  155. :class:`~django.http.HttpResponse` object. If it returns an
  156. :class:`~django.http.HttpResponse` object, the template response and response
  157. middleware will be applied and the resulting response returned to the
  158. browser. Otherwise, :ref:`default exception handling <error-views>` kicks in.
  159. Again, middleware are run in reverse order during the response phase, which
  160. includes ``process_exception``. If an exception middleware returns a response,
  161. the ``process_exception`` methods of the middleware classes above that
  162. middleware won't be called at all.
  163. .. _template-response-middleware:
  164. ``process_template_response()``
  165. -------------------------------
  166. .. method:: process_template_response(request, response)
  167. ``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is
  168. the :class:`~django.template.response.TemplateResponse` object (or equivalent)
  169. returned by a Django view or by a middleware.
  170. ``process_template_response()`` is called just after the view has finished
  171. executing, if the response instance has a ``render()`` method, indicating that
  172. it is a :class:`~django.template.response.TemplateResponse` or equivalent.
  173. It must return a response object that implements a ``render`` method. It could
  174. alter the given ``response`` by changing ``response.template_name`` and
  175. ``response.context_data``, or it could create and return a brand-new
  176. :class:`~django.template.response.TemplateResponse` or equivalent.
  177. You don't need to explicitly render responses -- responses will be
  178. automatically rendered once all template response middleware has been
  179. called.
  180. Middleware are run in reverse order during the response phase, which
  181. includes ``process_template_response()``.
  182. Dealing with streaming responses
  183. ================================
  184. Unlike :class:`~django.http.HttpResponse`,
  185. :class:`~django.http.StreamingHttpResponse` does not have a ``content``
  186. attribute. As a result, middleware can no longer assume that all responses
  187. will have a ``content`` attribute. If they need access to the content, they
  188. must test for streaming responses and adjust their behavior accordingly::
  189. if response.streaming:
  190. response.streaming_content = wrap_streaming_content(response.streaming_content)
  191. else:
  192. response.content = alter_content(response.content)
  193. .. note::
  194. ``streaming_content`` should be assumed to be too large to hold in memory.
  195. Response middleware may wrap it in a new generator, but must not consume
  196. it. Wrapping is typically implemented as follows::
  197. def wrap_streaming_content(content):
  198. for chunk in content:
  199. yield alter_content(chunk)
  200. Exception handling
  201. ==================
  202. Django automatically converts exceptions raised by the view or by middleware
  203. into an appropriate HTTP response with an error status code. :ref:`Certain
  204. exceptions <error-views>` are converted to 4xx status codes, while an unknown
  205. exception is converted to a 500 status code.
  206. This conversion takes place before and after each middleware (you can think of
  207. it as the thin film in between each layer of the onion), so that every
  208. middleware can always rely on getting some kind of HTTP response back from
  209. calling its ``get_response`` callable. Middleware don't need to worry about
  210. wrapping their call to ``get_response`` in a ``try/except`` and handling an
  211. exception that might have been raised by a later middleware or the view. Even
  212. if the very next middleware in the chain raises an
  213. :class:`~django.http.Http404` exception, for example, your middleware won't see
  214. that exception; instead it will get an :class:`~django.http.HttpResponse`
  215. object with a :attr:`~django.http.HttpResponse.status_code` of 404.
  216. You can set :setting:`DEBUG_PROPAGATE_EXCEPTIONS` to ``True`` to skip this
  217. conversion and propagate exceptions upwards.
  218. .. _async-middleware:
  219. Asynchronous support
  220. ====================
  221. Middleware can support any combination of synchronous and asynchronous
  222. requests. Django will adapt requests to fit the middleware's requirements if it
  223. cannot support both, but at a performance penalty.
  224. By default, Django assumes that your middleware is capable of handling only
  225. synchronous requests. To change these assumptions, set the following attributes
  226. on your middleware factory function or class:
  227. * ``sync_capable`` is a boolean indicating if the middleware can handle
  228. synchronous requests. Defaults to ``True``.
  229. * ``async_capable`` is a boolean indicating if the middleware can handle
  230. asynchronous requests. Defaults to ``False``.
  231. If your middleware has both ``sync_capable = True`` and
  232. ``async_capable = True``, then Django will pass it the request without
  233. converting it. In this case, you can work out if your middleware will receive
  234. async requests by checking if the ``get_response`` object you are passed is a
  235. coroutine function, using :py:func:`asyncio.iscoroutinefunction`.
  236. The ``django.utils.decorators`` module contains
  237. :func:`~django.utils.decorators.sync_only_middleware`,
  238. :func:`~django.utils.decorators.async_only_middleware`, and
  239. :func:`~django.utils.decorators.sync_and_async_middleware` decorators that
  240. allow you to apply these flags to middleware factory functions.
  241. The returned callable must match the sync or async nature of the
  242. ``get_response`` method. If you have an asynchronous ``get_response``, you must
  243. return a coroutine function (``async def``).
  244. ``process_view``, ``process_template_response`` and ``process_exception``
  245. methods, if they are provided, should also be adapted to match the sync/async
  246. mode. However, Django will individually adapt them as required if you do not,
  247. at an additional performance penalty.
  248. Here's an example of how to create a middleware function that supports both::
  249. import asyncio
  250. from django.utils.decorators import sync_and_async_middleware
  251. @sync_and_async_middleware
  252. def simple_middleware(get_response):
  253. # One-time configuration and initialization goes here.
  254. if asyncio.iscoroutinefunction(get_response):
  255. async def middleware(request):
  256. # Do something here!
  257. response = await get_response(request)
  258. return response
  259. else:
  260. def middleware(request):
  261. # Do something here!
  262. response = get_response(request)
  263. return response
  264. return middleware
  265. .. note::
  266. If you declare a hybrid middleware that supports both synchronous and
  267. asynchronous calls, the kind of call you get may not match the underlying
  268. view. Django will optimize the middleware call stack to have as few
  269. sync/async transitions as possible.
  270. Thus, even if you are wrapping an async view, you may be called in sync
  271. mode if there is other, synchronous middleware between you and the view.
  272. .. _upgrading-middleware:
  273. Upgrading pre-Django 1.10-style middleware
  274. ==========================================
  275. .. class:: django.utils.deprecation.MiddlewareMixin
  276. :module:
  277. Django provides ``django.utils.deprecation.MiddlewareMixin`` to ease creating
  278. middleware classes that are compatible with both :setting:`MIDDLEWARE` and the
  279. old ``MIDDLEWARE_CLASSES``, and support synchronous and asynchronous requests.
  280. All middleware classes included with Django are compatible with both settings.
  281. The mixin provides an ``__init__()`` method that requires a ``get_response``
  282. argument and stores it in ``self.get_response``.
  283. The ``__call__()`` method:
  284. #. Calls ``self.process_request(request)`` (if defined).
  285. #. Calls ``self.get_response(request)`` to get the response from later
  286. middleware and the view.
  287. #. Calls ``self.process_response(request, response)`` (if defined).
  288. #. Returns the response.
  289. If used with ``MIDDLEWARE_CLASSES``, the ``__call__()`` method will
  290. never be used; Django calls ``process_request()`` and ``process_response()``
  291. directly.
  292. In most cases, inheriting from this mixin will be sufficient to make an
  293. old-style middleware compatible with the new system with sufficient
  294. backwards-compatibility. The new short-circuiting semantics will be harmless or
  295. even beneficial to the existing middleware. In a few cases, a middleware class
  296. may need some changes to adjust to the new semantics.
  297. These are the behavioral differences between using :setting:`MIDDLEWARE` and
  298. ``MIDDLEWARE_CLASSES``:
  299. #. Under ``MIDDLEWARE_CLASSES``, every middleware will always have its
  300. ``process_response`` method called, even if an earlier middleware
  301. short-circuited by returning a response from its ``process_request``
  302. method. Under :setting:`MIDDLEWARE`, middleware behaves more like an onion:
  303. the layers that a response goes through on the way out are the same layers
  304. that saw the request on the way in. If a middleware short-circuits, only
  305. that middleware and the ones before it in :setting:`MIDDLEWARE` will see the
  306. response.
  307. #. Under ``MIDDLEWARE_CLASSES``, ``process_exception`` is applied to
  308. exceptions raised from a middleware ``process_request`` method. Under
  309. :setting:`MIDDLEWARE`, ``process_exception`` applies only to exceptions
  310. raised from the view (or from the ``render`` method of a
  311. :class:`~django.template.response.TemplateResponse`). Exceptions raised from
  312. a middleware are converted to the appropriate HTTP response and then passed
  313. to the next middleware.
  314. #. Under ``MIDDLEWARE_CLASSES``, if a ``process_response`` method raises
  315. an exception, the ``process_response`` methods of all earlier middleware are
  316. skipped and a ``500 Internal Server Error`` HTTP response is always
  317. returned (even if the exception raised was e.g. an
  318. :class:`~django.http.Http404`). Under :setting:`MIDDLEWARE`, an exception
  319. raised from a middleware will immediately be converted to the appropriate
  320. HTTP response, and then the next middleware in line will see that
  321. response. Middleware are never skipped due to a middleware raising an
  322. exception.