Debian Codegraph @

docs/topics/http/middleware.txt

raw
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 :class:`~django.http.StreamingHttpResponse` allows both synchronous and
271 asynchronous iterators. The wrapping function must match. Check
272 :attr:`StreamingHttpResponse.is_async
273 <django.http.StreamingHttpResponse.is_async>` if your middleware needs to
274 support both types of iterator.
275
276 Exception handling
277 ==================
278
279 Django automatically converts exceptions raised by the view or by middleware
280 into an appropriate HTTP response with an error status code. :ref:`Certain
281 exceptions <error-views>` are converted to 4xx status codes, while an unknown
282 exception is converted to a 500 status code.
283
284 This conversion takes place before and after each middleware (you can think of
285 it as the thin film in between each layer of the onion), so that every
286 middleware can always rely on getting some kind of HTTP response back from
287 calling its ``get_response`` callable. Middleware don't need to worry about
288 wrapping their call to ``get_response`` in a ``try/except`` and handling an
289 exception that might have been raised by a later middleware or the view. Even
290 if the very next middleware in the chain raises an
291 :class:`~django.http.Http404` exception, for example, your middleware won't see
292 that exception; instead it will get an :class:`~django.http.HttpResponse`
293 object with a :attr:`~django.http.HttpResponse.status_code` of 404.
294
295 You can set :setting:`DEBUG_PROPAGATE_EXCEPTIONS` to ``True`` to skip this
296 conversion and propagate exceptions upward.
297
298 .. _async-middleware:
299
300 Asynchronous support
301 ====================
302
303 Middleware can support any combination of synchronous and asynchronous
304 requests. Django will adapt requests to fit the middleware's requirements if it
305 cannot support both, but at a performance penalty.
306
307 By default, Django assumes that your middleware is capable of handling only
308 synchronous requests. To change these assumptions, set the following attributes
309 on your middleware factory function or class:
310
311 * ``sync_capable`` is a boolean indicating if the middleware can handle
312 synchronous requests. Defaults to ``True``.
313
314 * ``async_capable`` is a boolean indicating if the middleware can handle
315 asynchronous requests. Defaults to ``False``.
316
317 If your middleware has both ``sync_capable = True`` and
318 ``async_capable = True``, then Django will pass it the request without
319 converting it. In this case, you can work out if your middleware will receive
320 async requests by checking if the ``get_response`` object you are passed is a
321 coroutine function, using ``asgiref.sync.iscoroutinefunction``.
322
323 The ``django.utils.decorators`` module contains
324 :func:`~django.utils.decorators.sync_only_middleware`,
325 :func:`~django.utils.decorators.async_only_middleware`, and
326 :func:`~django.utils.decorators.sync_and_async_middleware` decorators that
327 allow you to apply these flags to middleware factory functions.
328
329 The returned callable must match the sync or async nature of the
330 ``get_response`` method. If you have an asynchronous ``get_response``, you must
331 return a coroutine function (``async def``).
332
333 ``process_view``, ``process_template_response`` and ``process_exception``
334 methods, if they are provided, should also be adapted to match the sync/async
335 mode. However, Django will individually adapt them as required if you do not,
336 at an additional performance penalty.
337
338 Here's an example of how to create a middleware function that supports both::
339
340 from asgiref.sync import iscoroutinefunction
341 from django.utils.decorators import sync_and_async_middleware
342
343
344 @sync_and_async_middleware
345 def simple_middleware(get_response):
346 # One-time configuration and initialization goes here.
347 if iscoroutinefunction(get_response):
348
349 async def middleware(request):
350 # Do something here!
351 response = await get_response(request)
352 return response
353
354 else:
355
356 def middleware(request):
357 # Do something here!
358 response = get_response(request)
359 return response
360
361 return middleware
362
363 .. note::
364
365 If you declare a hybrid middleware that supports both synchronous and
366 asynchronous calls, the kind of call you get may not match the underlying
367 view. Django will optimize the middleware call stack to have as few
368 sync/async transitions as possible.
369
370 Thus, even if you are wrapping an async view, you may be called in sync
371 mode if there is other, synchronous middleware between you and the view.
372
373 When using an asynchronous class-based middleware, you must ensure that
374 instances are correctly marked as coroutine functions::
375
376 from asgiref.sync import iscoroutinefunction, markcoroutinefunction
377
378
379 class AsyncMiddleware:
380 async_capable = True
381 sync_capable = False
382
383 def __init__(self, get_response):
384 self.get_response = get_response
385 if iscoroutinefunction(self.get_response):
386 markcoroutinefunction(self)
387
388 async def __call__(self, request):
389 response = await self.get_response(request)
390 # Some logic ...
391 return response
392
393 .. _upgrading-middleware:
394
395 Upgrading pre-Django 1.10-style middleware
396 ==========================================
397
398 .. class:: django.utils.deprecation.MiddlewareMixin
399 :module:
400
401 Django provides ``django.utils.deprecation.MiddlewareMixin`` to ease creating
402 middleware classes that are compatible with both :setting:`MIDDLEWARE` and the
403 old ``MIDDLEWARE_CLASSES``, and support synchronous and asynchronous requests.
404 All middleware classes included with Django are compatible with both settings.
405
406 The mixin provides an ``__init__()`` method that requires a ``get_response``
407 argument and stores it in ``self.get_response``.
408
409 The ``__call__()`` method:
410
411 #. Calls ``self.process_request(request)`` (if defined).
412 #. Calls ``self.get_response(request)`` to get the response from later
413 middleware and the view.
414 #. Calls ``self.process_response(request, response)`` (if defined).
415 #. Returns the response.
416
417 If used with ``MIDDLEWARE_CLASSES``, the ``__call__()`` method will
418 never be used; Django calls ``process_request()`` and ``process_response()``
419 directly.
420
421 In most cases, inheriting from this mixin will be sufficient to make an
422 old-style middleware compatible with the new system with sufficient
423 backwards-compatibility. The new short-circuiting semantics will be harmless or
424 even beneficial to the existing middleware. In a few cases, a middleware class
425 may need some changes to adjust to the new semantics.
426
427 These are the behavioral differences between using :setting:`MIDDLEWARE` and
428 ``MIDDLEWARE_CLASSES``:
429
430 #. Under ``MIDDLEWARE_CLASSES``, every middleware will always have its
431 ``process_response`` method called, even if an earlier middleware
432 short-circuited by returning a response from its ``process_request``
433 method. Under :setting:`MIDDLEWARE`, middleware behaves more like an onion:
434 the layers that a response goes through on the way out are the same layers
435 that saw the request on the way in. If a middleware short-circuits, only
436 that middleware and the ones before it in :setting:`MIDDLEWARE` will see the
437 response.
438
439 #. Under ``MIDDLEWARE_CLASSES``, ``process_exception`` is applied to
440 exceptions raised from a middleware ``process_request`` method. Under
441 :setting:`MIDDLEWARE`, ``process_exception`` applies only to exceptions
442 raised from the view (or from the ``render`` method of a
443 :class:`~django.template.response.TemplateResponse`). Exceptions raised from
444 a middleware are converted to the appropriate HTTP response and then passed
445 to the next middleware.
446
447 #. Under ``MIDDLEWARE_CLASSES``, if a ``process_response`` method raises
448 an exception, the ``process_response`` methods of all earlier middleware are
449 skipped and a ``500 Internal Server Error`` HTTP response is always
450 returned (even if the exception raised was e.g. an
451 :class:`~django.http.Http404`). Under :setting:`MIDDLEWARE`, an exception
452 raised from a middleware will immediately be converted to the appropriate
453 HTTP response, and then the next middleware in line will see that
454 response. Middleware are never skipped due to a middleware raising an
455 exception.