{"title":"Middleware","version":"4.0","locale":"it","docname":"topics/http/middleware","url":"/it/4.0/topics/http/middleware/","canonical":"https://djangodocs.dev/it/4.0/topics/http/middleware/","summary":"Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level «plugin» system for globally altering Django’s input…","html":"<h1>Middleware<a class=\"heading-anchor\" href=\"#middleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>Middleware is a framework of hooks into Django’s request/response processing.\nIt’s a light, low-level «plugin» system for globally altering Django’s input\nor output.</p>\n<p>Each middleware component is responsible for doing some specific function. For\nexample, Django includes a middleware component,\n<a class=\"reference internal\" href=\"/it/4.0/ref/middleware/#django.contrib.auth.middleware.AuthenticationMiddleware\" title=\"django.contrib.auth.middleware.AuthenticationMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">AuthenticationMiddleware</code></a>, that\nassociates users with requests using sessions.</p>\n<p>This document explains how middleware works, how you activate middleware, and\nhow to write your own middleware. Django ships with some built-in middleware\nyou can use right out of the box. They’re documented in the <a class=\"reference internal\" href=\"/it/4.0/ref/middleware/\"><span class=\"doc\">built-in\nmiddleware reference</span></a>.</p>\n<section id=\"writing-your-own-middleware\">\n<h2>Writing your own middleware<a class=\"heading-anchor\" href=\"#writing-your-own-middleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>A middleware factory is a callable that takes a <code class=\"docutils literal notranslate\">get_response</code> callable and\nreturns a middleware. A middleware is a callable that takes a request and\nreturns a response, just like a view.</p>\n<p>A middleware can be written as a function that looks like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">def</span> <span class=\"nf\">simple_middleware</span><span class=\"p\">(</span>get_response<span class=\"p\">):</span>\n    <span class=\"c1\"># One-time configuration and initialization.</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">middleware</span><span class=\"p\">(</span>request<span class=\"p\">):</span>\n        <span class=\"c1\"># Code to be executed for each request before</span>\n        <span class=\"c1\"># the view (and later middleware) are called.</span>\n\n        response <span class=\"o\">=</span> get_response<span class=\"p\">(</span>request<span class=\"p\">)</span>\n\n        <span class=\"c1\"># Code to be executed for each request/response after</span>\n        <span class=\"c1\"># the view is called.</span>\n\n        <span class=\"k\">return</span> response\n\n    <span class=\"k\">return</span> middleware\n</code></pre></div>\n<p>Or it can be written as a class whose instances are callable, like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">SimpleMiddleware</span><span class=\"p\">:</span>\n    <span class=\"k\">def</span> <span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> get_response<span class=\"p\">):</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>get_response <span class=\"o\">=</span> get_response\n        <span class=\"c1\"># One-time configuration and initialization.</span>\n\n    <span class=\"k\">def</span> <span class=\"fm\">__call__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> request<span class=\"p\">):</span>\n        <span class=\"c1\"># Code to be executed for each request before</span>\n        <span class=\"c1\"># the view (and later middleware) are called.</span>\n\n        response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>get_response<span class=\"p\">(</span>request<span class=\"p\">)</span>\n\n        <span class=\"c1\"># Code to be executed for each request/response after</span>\n        <span class=\"c1\"># the view is called.</span>\n\n        <span class=\"k\">return</span> response\n</code></pre></div>\n<p>The <code class=\"docutils literal notranslate\">get_response</code> callable provided by Django might be the actual view (if\nthis is the last listed middleware) or it might be the next middleware in the\nchain. The current middleware doesn’t need to know or care what exactly it is,\njust that it represents whatever comes next.</p>\n<p>The above is a slight simplification – the <code class=\"docutils literal notranslate\">get_response</code> callable for the\nlast middleware in the chain won’t be the actual view but rather a wrapper\nmethod from the handler which takes care of applying <a class=\"reference internal\" href=\"#view-middleware\"><span class=\"std std-ref\">view middleware</span></a>, calling the view with appropriate URL arguments, and\napplying <a class=\"reference internal\" href=\"#template-response-middleware\"><span class=\"std std-ref\">template-response</span></a> and\n<a class=\"reference internal\" href=\"#exception-middleware\"><span class=\"std std-ref\">exception</span></a> middleware.</p>\n<p>Middleware can either support only synchronous Python (the default), only\nasynchronous Python, or both. See <a class=\"reference internal\" href=\"#async-middleware\"><span class=\"std std-ref\">Asynchronous support</span></a> for details of how to\nadvertise what you support, and know what kind of request you are getting.</p>\n<p>Middleware can live anywhere on your Python path.</p>\n<section id=\"init-get-response\">\n<h3><code class=\"docutils literal notranslate\">__init__(get_response)</code><a class=\"heading-anchor\" href=\"#init-get-response\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Middleware factories must accept a <code class=\"docutils literal notranslate\">get_response</code> argument. You can also\ninitialize some global state for the middleware. Keep in mind a couple of\ncaveats:</p>\n<ul class=\"simple\">\n<li><p>Django initializes your middleware with only the <code class=\"docutils literal notranslate\">get_response</code> argument,\nso you can’t define <code class=\"docutils literal notranslate\">__init__()</code> as requiring any other arguments.</p></li>\n<li><p>Unlike the <code class=\"docutils literal notranslate\">__call__()</code> method which is called once per request,\n<code class=\"docutils literal notranslate\">__init__()</code> is called only <em>once</em>, when the web server starts.</p></li>\n</ul>\n</section>\n<section id=\"marking-middleware-as-unused\">\n<h3>Marking middleware as unused<a class=\"heading-anchor\" href=\"#marking-middleware-as-unused\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>It’s sometimes useful to determine at startup time whether a piece of\nmiddleware should be used. In these cases, your middleware’s <code class=\"docutils literal notranslate\">__init__()</code>\nmethod may raise <a class=\"reference internal\" href=\"/it/4.0/ref/exceptions/#django.core.exceptions.MiddlewareNotUsed\" title=\"django.core.exceptions.MiddlewareNotUsed\"><code class=\"xref py py-exc docutils literal notranslate\">MiddlewareNotUsed</code></a>. Django will\nthen remove that middleware from the middleware process and log a debug message\nto the <a class=\"reference internal\" href=\"/it/4.0/ref/logging/#django-request-logger\"><span class=\"std std-ref\">django.request</span></a> logger when <a class=\"reference internal\" href=\"/it/4.0/ref/settings/#std-setting-DEBUG\"><code class=\"xref std std-setting docutils literal notranslate\">DEBUG</code></a> is <code class=\"docutils literal notranslate\">True</code>.</p>\n</section>\n</section>\n<section id=\"activating-middleware\">\n<h2>Activating middleware<a class=\"heading-anchor\" href=\"#activating-middleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>To activate a middleware component, add it to the <a class=\"reference internal\" href=\"/it/4.0/ref/settings/#std-setting-MIDDLEWARE\"><code class=\"xref std std-setting docutils literal notranslate\">MIDDLEWARE</code></a> list in\nyour Django settings.</p>\n<p>In <a class=\"reference internal\" href=\"/it/4.0/ref/settings/#std-setting-MIDDLEWARE\"><code class=\"xref std std-setting docutils literal notranslate\">MIDDLEWARE</code></a>, each middleware component is represented by a string:\nthe full Python path to the middleware factory’s class or function name. For\nexample, here’s the default value created by <a class=\"reference internal\" href=\"/it/4.0/ref/django-admin/#django-admin-startproject\"><code class=\"xref std std-djadmin docutils literal notranslate\">django-admin\nstartproject</code></a>:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>MIDDLEWARE <span class=\"o\">=</span> <span class=\"p\">[</span>\n    <span class=\"s1\">&#39;django.middleware.security.SecurityMiddleware&#39;</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;django.contrib.sessions.middleware.SessionMiddleware&#39;</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;django.middleware.common.CommonMiddleware&#39;</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;django.middleware.csrf.CsrfViewMiddleware&#39;</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;django.contrib.messages.middleware.MessageMiddleware&#39;</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;</span><span class=\"p\">,</span>\n<span class=\"p\">]</span>\n</code></pre></div>\n<p>A Django installation doesn’t require any middleware — <a class=\"reference internal\" href=\"/it/4.0/ref/settings/#std-setting-MIDDLEWARE\"><code class=\"xref std std-setting docutils literal notranslate\">MIDDLEWARE</code></a>\ncan be empty, if you’d like — but it’s strongly suggested that you at least use\n<a class=\"reference internal\" href=\"/it/4.0/ref/middleware/#django.middleware.common.CommonMiddleware\" title=\"django.middleware.common.CommonMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">CommonMiddleware</code></a>.</p>\n<p>The order in <a class=\"reference internal\" href=\"/it/4.0/ref/settings/#std-setting-MIDDLEWARE\"><code class=\"xref std std-setting docutils literal notranslate\">MIDDLEWARE</code></a> matters because a middleware can depend on\nother middleware. For instance,\n<a class=\"reference internal\" href=\"/it/4.0/ref/middleware/#django.contrib.auth.middleware.AuthenticationMiddleware\" title=\"django.contrib.auth.middleware.AuthenticationMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">AuthenticationMiddleware</code></a> stores the\nauthenticated user in the session; therefore, it must run after\n<a class=\"reference internal\" href=\"/it/4.0/ref/middleware/#django.contrib.sessions.middleware.SessionMiddleware\" title=\"django.contrib.sessions.middleware.SessionMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">SessionMiddleware</code></a>. See\n<a class=\"reference internal\" href=\"/it/4.0/ref/middleware/#middleware-ordering\"><span class=\"std std-ref\">Middleware ordering</span></a> for some common hints about ordering of Django\nmiddleware classes.</p>\n</section>\n<section id=\"middleware-order-and-layering\">\n<h2>Middleware order and layering<a class=\"heading-anchor\" href=\"#middleware-order-and-layering\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>During the request phase, before calling the view, Django applies middleware in\nthe order it’s defined in <a class=\"reference internal\" href=\"/it/4.0/ref/settings/#std-setting-MIDDLEWARE\"><code class=\"xref std std-setting docutils literal notranslate\">MIDDLEWARE</code></a>, top-down.</p>\n<p>You can think of it like an onion: each middleware class is a «layer» that\nwraps the view, which is in the core of the onion. If the request passes\nthrough all the layers of the onion (each one calls <code class=\"docutils literal notranslate\">get_response</code> to pass\nthe request in to the next layer), all the way to the view at the core, the\nresponse will then pass through every layer (in reverse order) on the way back\nout.</p>\n<p>If one of the layers decides to short-circuit and return a response without\never calling its <code class=\"docutils literal notranslate\">get_response</code>, none of the layers of the onion inside that\nlayer (including the view) will see the request or the response. The response\nwill only return through the same layers that the request passed in through.</p>\n</section>\n<section id=\"other-middleware-hooks\">\n<h2>Other middleware hooks<a class=\"heading-anchor\" href=\"#other-middleware-hooks\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Besides the basic request/response middleware pattern described earlier, you\ncan add three other special methods to class-based middleware:</p>\n<section id=\"process-view\">\n<span id=\"view-middleware\"></span><h3><code class=\"docutils literal notranslate\">process_view()</code><a class=\"heading-anchor\" href=\"#process-view\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"process_view\">\n<span class=\"sig-name descname\">process_view</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">request</em>, <em class=\"sig-param\">view_func</em>, <em class=\"sig-param\">view_args</em>, <em class=\"sig-param\">view_kwargs</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#process_view\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p><code class=\"docutils literal notranslate\">request</code> is an <a class=\"reference internal\" href=\"/it/4.0/ref/request-response/#django.http.HttpRequest\" title=\"django.http.HttpRequest\"><code class=\"xref py py-class docutils literal notranslate\">HttpRequest</code></a> object. <code class=\"docutils literal notranslate\">view_func</code> is\nthe Python function that Django is about to use. (It’s the actual function\nobject, not the name of the function as a string.) <code class=\"docutils literal notranslate\">view_args</code> is a list of\npositional arguments that will be passed to the view, and <code class=\"docutils literal notranslate\">view_kwargs</code> is a\ndictionary of keyword arguments that will be passed to the view. Neither\n<code class=\"docutils literal notranslate\">view_args</code> nor <code class=\"docutils literal notranslate\">view_kwargs</code> include the first view argument\n(<code class=\"docutils literal notranslate\">request</code>).</p>\n<p><code class=\"docutils literal notranslate\">process_view()</code> is called just before Django calls the view.</p>\n<p>It should return either <code class=\"docutils literal notranslate\">None</code> or an <a class=\"reference internal\" href=\"/it/4.0/ref/request-response/#django.http.HttpResponse\" title=\"django.http.HttpResponse\"><code class=\"xref py py-class docutils literal notranslate\">HttpResponse</code></a>\nobject. If it returns <code class=\"docutils literal notranslate\">None</code>, Django will continue processing this request,\nexecuting any other <code class=\"docutils literal notranslate\">process_view()</code> middleware and, then, the appropriate\nview. If it returns an <a class=\"reference internal\" href=\"/it/4.0/ref/request-response/#django.http.HttpResponse\" title=\"django.http.HttpResponse\"><code class=\"xref py py-class docutils literal notranslate\">HttpResponse</code></a> object, Django won’t\nbother calling the appropriate view; it’ll apply response middleware to that\n<a class=\"reference internal\" href=\"/it/4.0/ref/request-response/#django.http.HttpResponse\" title=\"django.http.HttpResponse\"><code class=\"xref py py-class docutils literal notranslate\">HttpResponse</code></a> and return the result.</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Nota</p>\n<p>Accessing <a class=\"reference internal\" href=\"/it/4.0/ref/request-response/#django.http.HttpRequest.POST\" title=\"django.http.HttpRequest.POST\"><code class=\"xref py py-attr docutils literal notranslate\">request.POST</code></a> inside\nmiddleware before the view runs or in <code class=\"docutils literal notranslate\">process_view()</code> will prevent any\nview running after the middleware from being able to <a class=\"reference internal\" href=\"/it/4.0/topics/http/file-uploads/#modifying-upload-handlers-on-the-fly\"><span class=\"std std-ref\">modify the\nupload handlers for the request</span></a>,\nand should normally be avoided.</p>\n<p>The <a class=\"reference internal\" href=\"/it/4.0/ref/middleware/#django.middleware.csrf.CsrfViewMiddleware\" title=\"django.middleware.csrf.CsrfViewMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">CsrfViewMiddleware</code></a> class can be\nconsidered an exception, as it provides the\n<a class=\"reference internal\" href=\"/it/4.0/ref/csrf/#django.views.decorators.csrf.csrf_exempt\" title=\"django.views.decorators.csrf.csrf_exempt\"><code class=\"xref py py-func docutils literal notranslate\">csrf_exempt()</code></a> and\n<a class=\"reference internal\" href=\"/it/4.0/ref/csrf/#django.views.decorators.csrf.csrf_protect\" title=\"django.views.decorators.csrf.csrf_protect\"><code class=\"xref py py-func docutils literal notranslate\">csrf_protect()</code></a> decorators which allow\nviews to explicitly control at what point the CSRF validation should occur.</p>\n</aside>\n</section>\n<section id=\"process-exception\">\n<span id=\"exception-middleware\"></span><h3><code class=\"docutils literal notranslate\">process_exception()</code><a class=\"heading-anchor\" href=\"#process-exception\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"process_exception\">\n<span class=\"sig-name descname\">process_exception</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">request</em>, <em class=\"sig-param\">exception</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#process_exception\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p><code class=\"docutils literal notranslate\">request</code> is an <a class=\"reference internal\" href=\"/it/4.0/ref/request-response/#django.http.HttpRequest\" title=\"django.http.HttpRequest\"><code class=\"xref py py-class docutils literal notranslate\">HttpRequest</code></a> object. <code class=\"docutils literal notranslate\">exception</code> is an\n<code class=\"docutils literal notranslate\">Exception</code> object raised by the view function.</p>\n<p>Django calls <code class=\"docutils literal notranslate\">process_exception()</code> when a view raises an exception.\n<code class=\"docutils literal notranslate\">process_exception()</code> should return either <code class=\"docutils literal notranslate\">None</code> or an\n<a class=\"reference internal\" href=\"/it/4.0/ref/request-response/#django.http.HttpResponse\" title=\"django.http.HttpResponse\"><code class=\"xref py py-class docutils literal notranslate\">HttpResponse</code></a> object. If it returns an\n<a class=\"reference internal\" href=\"/it/4.0/ref/request-response/#django.http.HttpResponse\" title=\"django.http.HttpResponse\"><code class=\"xref py py-class docutils literal notranslate\">HttpResponse</code></a> object, the template response and response\nmiddleware will be applied and the resulting response returned to the\nbrowser. Otherwise, <a class=\"reference internal\" href=\"/it/4.0/ref/views/#error-views\"><span class=\"std std-ref\">default exception handling</span></a> kicks in.</p>\n<p>Again, middleware are run in reverse order during the response phase, which\nincludes <code class=\"docutils literal notranslate\">process_exception</code>. If an exception middleware returns a response,\nthe <code class=\"docutils literal notranslate\">process_exception</code> methods of the middleware classes above that\nmiddleware won’t be called at all.</p>\n</section>\n<section id=\"process-template-response\">\n<span id=\"template-response-middleware\"></span><h3><code class=\"docutils literal notranslate\">process_template_response()</code><a class=\"heading-anchor\" href=\"#process-template-response\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"process_template_response\">\n<span class=\"sig-name descname\">process_template_response</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">request</em>, <em class=\"sig-param\">response</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#process_template_response\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p><code class=\"docutils literal notranslate\">request</code> is an <a class=\"reference internal\" href=\"/it/4.0/ref/request-response/#django.http.HttpRequest\" title=\"django.http.HttpRequest\"><code class=\"xref py py-class docutils literal notranslate\">HttpRequest</code></a> object. <code class=\"docutils literal notranslate\">response</code> is\nthe <a class=\"reference internal\" href=\"/it/4.0/ref/template-response/#django.template.response.TemplateResponse\" title=\"django.template.response.TemplateResponse\"><code class=\"xref py py-class docutils literal notranslate\">TemplateResponse</code></a> object (or equivalent)\nreturned by a Django view or by a middleware.</p>\n<p><code class=\"docutils literal notranslate\">process_template_response()</code> is called just after the view has finished\nexecuting, if the response instance has a <code class=\"docutils literal notranslate\">render()</code> method, indicating that\nit is a <a class=\"reference internal\" href=\"/it/4.0/ref/template-response/#django.template.response.TemplateResponse\" title=\"django.template.response.TemplateResponse\"><code class=\"xref py py-class docutils literal notranslate\">TemplateResponse</code></a> or equivalent.</p>\n<p>It must return a response object that implements a <code class=\"docutils literal notranslate\">render</code> method. It could\nalter the given <code class=\"docutils literal notranslate\">response</code> by changing <code class=\"docutils literal notranslate\">response.template_name</code> and\n<code class=\"docutils literal notranslate\">response.context_data</code>, or it could create and return a brand-new\n<a class=\"reference internal\" href=\"/it/4.0/ref/template-response/#django.template.response.TemplateResponse\" title=\"django.template.response.TemplateResponse\"><code class=\"xref py py-class docutils literal notranslate\">TemplateResponse</code></a> or equivalent.</p>\n<p>You don’t need to explicitly render responses – responses will be\nautomatically rendered once all template response middleware has been\ncalled.</p>\n<p>Middleware are run in reverse order during the response phase, which\nincludes <code class=\"docutils literal notranslate\">process_template_response()</code>.</p>\n</section>\n</section>\n<section id=\"dealing-with-streaming-responses\">\n<h2>Dealing with streaming responses<a class=\"heading-anchor\" href=\"#dealing-with-streaming-responses\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Unlike <a class=\"reference internal\" href=\"/it/4.0/ref/request-response/#django.http.HttpResponse\" title=\"django.http.HttpResponse\"><code class=\"xref py py-class docutils literal notranslate\">HttpResponse</code></a>,\n<a class=\"reference internal\" href=\"/it/4.0/ref/request-response/#django.http.StreamingHttpResponse\" title=\"django.http.StreamingHttpResponse\"><code class=\"xref py py-class docutils literal notranslate\">StreamingHttpResponse</code></a> does not have a <code class=\"docutils literal notranslate\">content</code>\nattribute. As a result, middleware can no longer assume that all responses\nwill have a <code class=\"docutils literal notranslate\">content</code> attribute. If they need access to the content, they\nmust test for streaming responses and adjust their behavior accordingly:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">if</span> response<span class=\"o\">.</span>streaming<span class=\"p\">:</span>\n    response<span class=\"o\">.</span>streaming_content <span class=\"o\">=</span> wrap_streaming_content<span class=\"p\">(</span>response<span class=\"o\">.</span>streaming_content<span class=\"p\">)</span>\n<span class=\"k\">else</span><span class=\"p\">:</span>\n    response<span class=\"o\">.</span>content <span class=\"o\">=</span> alter_content<span class=\"p\">(</span>response<span class=\"o\">.</span>content<span class=\"p\">)</span>\n</code></pre></div>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Nota</p>\n<p><code class=\"docutils literal notranslate\">streaming_content</code> should be assumed to be too large to hold in memory.\nResponse middleware may wrap it in a new generator, but must not consume\nit. Wrapping is typically implemented as follows:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">def</span> <span class=\"nf\">wrap_streaming_content</span><span class=\"p\">(</span>content<span class=\"p\">):</span>\n    <span class=\"k\">for</span> chunk <span class=\"ow\">in</span> content<span class=\"p\">:</span>\n        <span class=\"k\">yield</span> alter_content<span class=\"p\">(</span>chunk<span class=\"p\">)</span>\n</code></pre></div>\n</aside>\n</section>\n<section id=\"exception-handling\">\n<h2>Exception handling<a class=\"heading-anchor\" href=\"#exception-handling\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Django automatically converts exceptions raised by the view or by middleware\ninto an appropriate HTTP response with an error status code. <a class=\"reference internal\" href=\"/it/4.0/ref/views/#error-views\"><span class=\"std std-ref\">Certain\nexceptions</span></a> are converted to 4xx status codes, while an unknown\nexception is converted to a 500 status code.</p>\n<p>This conversion takes place before and after each middleware (you can think of\nit as the thin film in between each layer of the onion), so that every\nmiddleware can always rely on getting some kind of HTTP response back from\ncalling its <code class=\"docutils literal notranslate\">get_response</code> callable. Middleware don’t need to worry about\nwrapping their call to <code class=\"docutils literal notranslate\">get_response</code> in a <code class=\"docutils literal notranslate\">try/except</code> and handling an\nexception that might have been raised by a later middleware or the view. Even\nif the very next middleware in the chain raises an\n<a class=\"reference internal\" href=\"/it/4.0/topics/http/views/#django.http.Http404\" title=\"django.http.Http404\"><code class=\"xref py py-class docutils literal notranslate\">Http404</code></a> exception, for example, your middleware won’t see\nthat exception; instead it will get an <a class=\"reference internal\" href=\"/it/4.0/ref/request-response/#django.http.HttpResponse\" title=\"django.http.HttpResponse\"><code class=\"xref py py-class docutils literal notranslate\">HttpResponse</code></a>\nobject with a <a class=\"reference internal\" href=\"/it/4.0/ref/request-response/#django.http.HttpResponse.status_code\" title=\"django.http.HttpResponse.status_code\"><code class=\"xref py py-attr docutils literal notranslate\">status_code</code></a> of 404.</p>\n<p>You can set <a class=\"reference internal\" href=\"/it/4.0/ref/settings/#std-setting-DEBUG_PROPAGATE_EXCEPTIONS\"><code class=\"xref std std-setting docutils literal notranslate\">DEBUG_PROPAGATE_EXCEPTIONS</code></a> to <code class=\"docutils literal notranslate\">True</code> to skip this\nconversion and propagate exceptions upward.</p>\n</section>\n<section id=\"asynchronous-support\">\n<span id=\"async-middleware\"></span><h2>Asynchronous support<a class=\"heading-anchor\" href=\"#asynchronous-support\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Middleware can support any combination of synchronous and asynchronous\nrequests. Django will adapt requests to fit the middleware’s requirements if it\ncannot support both, but at a performance penalty.</p>\n<p>By default, Django assumes that your middleware is capable of handling only\nsynchronous requests. To change these assumptions, set the following attributes\non your middleware factory function or class:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\">sync_capable</code> is a boolean indicating if the middleware can handle\nsynchronous requests. Defaults to <code class=\"docutils literal notranslate\">True</code>.</p></li>\n<li><p><code class=\"docutils literal notranslate\">async_capable</code> is a boolean indicating if the middleware can handle\nasynchronous requests. Defaults to <code class=\"docutils literal notranslate\">False</code>.</p></li>\n</ul>\n<p>If your middleware has both <code class=\"docutils literal notranslate\">sync_capable = True</code> and\n<code class=\"docutils literal notranslate\">async_capable = True</code>, then Django will pass it the request without\nconverting it. In this case, you can work out if your middleware will receive\nasync requests by checking if the <code class=\"docutils literal notranslate\">get_response</code> object you are passed is a\ncoroutine function, using <code class=\"docutils literal notranslate\">asyncio.iscoroutinefunction</code>.</p>\n<p>The <code class=\"docutils literal notranslate\">django.utils.decorators</code> module contains\n<a class=\"reference internal\" href=\"/it/4.0/ref/utils/#django.utils.decorators.sync_only_middleware\" title=\"django.utils.decorators.sync_only_middleware\"><code class=\"xref py py-func docutils literal notranslate\">sync_only_middleware()</code></a>,\n<a class=\"reference internal\" href=\"/it/4.0/ref/utils/#django.utils.decorators.async_only_middleware\" title=\"django.utils.decorators.async_only_middleware\"><code class=\"xref py py-func docutils literal notranslate\">async_only_middleware()</code></a>, and\n<a class=\"reference internal\" href=\"/it/4.0/ref/utils/#django.utils.decorators.sync_and_async_middleware\" title=\"django.utils.decorators.sync_and_async_middleware\"><code class=\"xref py py-func docutils literal notranslate\">sync_and_async_middleware()</code></a> decorators that\nallow you to apply these flags to middleware factory functions.</p>\n<p>The returned callable must match the sync or async nature of the\n<code class=\"docutils literal notranslate\">get_response</code> method. If you have an asynchronous <code class=\"docutils literal notranslate\">get_response</code>, you must\nreturn a coroutine function (<code class=\"docutils literal notranslate\">async def</code>).</p>\n<p><code class=\"docutils literal notranslate\">process_view</code>, <code class=\"docutils literal notranslate\">process_template_response</code> and <code class=\"docutils literal notranslate\">process_exception</code>\nmethods, if they are provided, should also be adapted to match the sync/async\nmode. However, Django will individually adapt them as required if you do not,\nat an additional performance penalty.</p>\n<p>Here’s an example of how to create a middleware function that supports both:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">import</span> <span class=\"nn\">asyncio</span>\n<span class=\"kn\">from</span> <span class=\"nn\">django.utils.decorators</span> <span class=\"kn\">import</span> sync_and_async_middleware\n\n<span class=\"nd\">@sync_and_async_middleware</span>\n<span class=\"k\">def</span> <span class=\"nf\">simple_middleware</span><span class=\"p\">(</span>get_response<span class=\"p\">):</span>\n    <span class=\"c1\"># One-time configuration and initialization goes here.</span>\n    <span class=\"k\">if</span> asyncio<span class=\"o\">.</span>iscoroutinefunction<span class=\"p\">(</span>get_response<span class=\"p\">):</span>\n        <span class=\"k\">async</span> <span class=\"k\">def</span> <span class=\"nf\">middleware</span><span class=\"p\">(</span>request<span class=\"p\">):</span>\n            <span class=\"c1\"># Do something here!</span>\n            response <span class=\"o\">=</span> <span class=\"k\">await</span> get_response<span class=\"p\">(</span>request<span class=\"p\">)</span>\n            <span class=\"k\">return</span> response\n\n    <span class=\"k\">else</span><span class=\"p\">:</span>\n        <span class=\"k\">def</span> <span class=\"nf\">middleware</span><span class=\"p\">(</span>request<span class=\"p\">):</span>\n            <span class=\"c1\"># Do something here!</span>\n            response <span class=\"o\">=</span> get_response<span class=\"p\">(</span>request<span class=\"p\">)</span>\n            <span class=\"k\">return</span> response\n\n    <span class=\"k\">return</span> middleware\n</code></pre></div>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Nota</p>\n<p>If you declare a hybrid middleware that supports both synchronous and\nasynchronous calls, the kind of call you get may not match the underlying\nview. Django will optimize the middleware call stack to have as few\nsync/async transitions as possible.</p>\n<p>Thus, even if you are wrapping an async view, you may be called in sync\nmode if there is other, synchronous middleware between you and the view.</p>\n</aside>\n</section>\n<section id=\"upgrading-pre-django-1-10-style-middleware\">\n<span id=\"upgrading-middleware\"></span><h2>Upgrading pre-Django 1.10-style middleware<a class=\"heading-anchor\" href=\"#upgrading-pre-django-1-10-style-middleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.utils.deprecation.MiddlewareMixin\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-prename descclassname\">django.utils.deprecation.</span><span class=\"sig-name descname\">MiddlewareMixin</span><a class=\"heading-anchor\" href=\"#django.utils.deprecation.MiddlewareMixin\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Django provides <code class=\"docutils literal notranslate\">django.utils.deprecation.MiddlewareMixin</code> to ease creating\nmiddleware classes that are compatible with both <a class=\"reference internal\" href=\"/it/4.0/ref/settings/#std-setting-MIDDLEWARE\"><code class=\"xref std std-setting docutils literal notranslate\">MIDDLEWARE</code></a> and the\nold <code class=\"docutils literal notranslate\">MIDDLEWARE_CLASSES</code>, and support synchronous and asynchronous requests.\nAll middleware classes included with Django are compatible with both settings.</p>\n<p>The mixin provides an <code class=\"docutils literal notranslate\">__init__()</code> method that requires a <code class=\"docutils literal notranslate\">get_response</code>\nargument and stores it in <code class=\"docutils literal notranslate\">self.get_response</code>.</p>\n<p>The <code class=\"docutils literal notranslate\">__call__()</code> method:</p>\n<ol class=\"arabic simple\">\n<li><p>Calls <code class=\"docutils literal notranslate\">self.process_request(request)</code> (if defined).</p></li>\n<li><p>Calls <code class=\"docutils literal notranslate\">self.get_response(request)</code> to get the response from later\nmiddleware and the view.</p></li>\n<li><p>Calls <code class=\"docutils literal notranslate\">self.process_response(request, response)</code> (if defined).</p></li>\n<li><p>Returns the response.</p></li>\n</ol>\n<p>If used with <code class=\"docutils literal notranslate\">MIDDLEWARE_CLASSES</code>, the <code class=\"docutils literal notranslate\">__call__()</code> method will\nnever be used; Django calls <code class=\"docutils literal notranslate\">process_request()</code> and <code class=\"docutils literal notranslate\">process_response()</code>\ndirectly.</p>\n<p>In most cases, inheriting from this mixin will be sufficient to make an\nold-style middleware compatible with the new system with sufficient\nbackwards-compatibility. The new short-circuiting semantics will be harmless or\neven beneficial to the existing middleware. In a few cases, a middleware class\nmay need some changes to adjust to the new semantics.</p>\n<p>These are the behavioral differences between using <a class=\"reference internal\" href=\"/it/4.0/ref/settings/#std-setting-MIDDLEWARE\"><code class=\"xref std std-setting docutils literal notranslate\">MIDDLEWARE</code></a> and\n<code class=\"docutils literal notranslate\">MIDDLEWARE_CLASSES</code>:</p>\n<ol class=\"arabic simple\">\n<li><p>Under <code class=\"docutils literal notranslate\">MIDDLEWARE_CLASSES</code>, every middleware will always have its\n<code class=\"docutils literal notranslate\">process_response</code> method called, even if an earlier middleware\nshort-circuited by returning a response from its <code class=\"docutils literal notranslate\">process_request</code>\nmethod. Under <a class=\"reference internal\" href=\"/it/4.0/ref/settings/#std-setting-MIDDLEWARE\"><code class=\"xref std std-setting docutils literal notranslate\">MIDDLEWARE</code></a>, middleware behaves more like an onion:\nthe layers that a response goes through on the way out are the same layers\nthat saw the request on the way in. If a middleware short-circuits, only\nthat middleware and the ones before it in <a class=\"reference internal\" href=\"/it/4.0/ref/settings/#std-setting-MIDDLEWARE\"><code class=\"xref std std-setting docutils literal notranslate\">MIDDLEWARE</code></a> will see the\nresponse.</p></li>\n<li><p>Under <code class=\"docutils literal notranslate\">MIDDLEWARE_CLASSES</code>, <code class=\"docutils literal notranslate\">process_exception</code> is applied to\nexceptions raised from a middleware <code class=\"docutils literal notranslate\">process_request</code> method. Under\n<a class=\"reference internal\" href=\"/it/4.0/ref/settings/#std-setting-MIDDLEWARE\"><code class=\"xref std std-setting docutils literal notranslate\">MIDDLEWARE</code></a>, <code class=\"docutils literal notranslate\">process_exception</code> applies only to exceptions\nraised from the view (or from the <code class=\"docutils literal notranslate\">render</code> method of a\n<a class=\"reference internal\" href=\"/it/4.0/ref/template-response/#django.template.response.TemplateResponse\" title=\"django.template.response.TemplateResponse\"><code class=\"xref py py-class docutils literal notranslate\">TemplateResponse</code></a>). Exceptions raised from\na middleware are converted to the appropriate HTTP response and then passed\nto the next middleware.</p></li>\n<li><p>Under <code class=\"docutils literal notranslate\">MIDDLEWARE_CLASSES</code>, if a <code class=\"docutils literal notranslate\">process_response</code> method raises\nan exception, the <code class=\"docutils literal notranslate\">process_response</code> methods of all earlier middleware are\nskipped and a <code class=\"docutils literal notranslate\">500 Internal Server Error</code> HTTP response is always\nreturned (even if the exception raised was e.g. an\n<a class=\"reference internal\" href=\"/it/4.0/topics/http/views/#django.http.Http404\" title=\"django.http.Http404\"><code class=\"xref py py-class docutils literal notranslate\">Http404</code></a>). Under <a class=\"reference internal\" href=\"/it/4.0/ref/settings/#std-setting-MIDDLEWARE\"><code class=\"xref std std-setting docutils literal notranslate\">MIDDLEWARE</code></a>, an exception\nraised from a middleware will immediately be converted to the appropriate\nHTTP response, and then the next middleware in line will see that\nresponse. Middleware are never skipped due to a middleware raising an\nexception.</p></li>\n</ol>\n</section>","rootId":"middleware","toc":[{"title":"Writing your own middleware","anchor":"writing-your-own-middleware","children":[{"title":"__init__(get_response)","anchor":"init-get-response","children":[]},{"title":"Marking middleware as unused","anchor":"marking-middleware-as-unused","children":[]}]},{"title":"Activating middleware","anchor":"activating-middleware","children":[]},{"title":"Middleware order and layering","anchor":"middleware-order-and-layering","children":[]},{"title":"Other middleware hooks","anchor":"other-middleware-hooks","children":[{"title":"process_view()","anchor":"process-view","children":[]},{"title":"process_exception()","anchor":"process-exception","children":[]},{"title":"process_template_response()","anchor":"process-template-response","children":[]}]},{"title":"Dealing with streaming responses","anchor":"dealing-with-streaming-responses","children":[]},{"title":"Exception handling","anchor":"exception-handling","children":[]},{"title":"Asynchronous support","anchor":"asynchronous-support","children":[]},{"title":"Upgrading pre-Django 1.10-style middleware","anchor":"upgrading-pre-django-1-10-style-middleware","children":[]}],"breadcrumbs":[{"docname":"topics/index","title":"Using Django","url":"/it/4.0/topics/"},{"docname":"topics/http/index","title":"Handling HTTP requests","url":"/it/4.0/topics/http/"}],"prev":{"docname":"topics/http/generic-views","title":"Generic views","url":"/it/4.0/topics/http/generic-views/"},"next":{"docname":"topics/http/sessions","title":"How to use sessions","url":"/it/4.0/topics/http/sessions/"},"formats":{"html":"/it/4.0/topics/http/middleware/","markdown":"/it/4.0/topics/http/middleware.md","json":"/it/4.0/topics/http/middleware.json"},"source":"https://github.com/django/django/blob/stable/4.0.x/docs/topics/http/middleware.txt","official":"https://docs.djangoproject.com/it/4.0/topics/http/middleware/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2"],"inLocales":["en","zh-hans","fr","ja","id","it","pt-br","ko","es","el","pl"]}