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