<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang=""> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Middleware — Django 1.8.19 documentation</title> <link rel="stylesheet" href="../../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../../', VERSION: '1.8.19', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <link rel="index" title="Index" href="../../genindex.html" /> <link rel="search" title="Search" href="../../search.html" /> <link rel="top" title="Django 1.8.19 documentation" href="../../contents.html" /> <link rel="up" title="Handling HTTP requests" href="index.html" /> <link rel="next" title="How to use sessions" href="sessions.html" /> <link rel="prev" title="Generic views" href="generic-views.html" /> <script type="text/javascript" src="../../templatebuiltins.js"></script> <script type="text/javascript"> (function($) { if (!django_template_builtins) { // templatebuiltins.js missing, do nothing. return; } $(document).ready(function() { // Hyperlink Django template tags and filters var base = "../../ref/templates/builtins.html"; if (base == "#") { // Special case for builtins.html itself base = ""; } // Tags are keywords, class '.k' $("div.highlight\\-html\\+django span.k").each(function(i, elem) { var tagname = $(elem).text(); if ($.inArray(tagname, django_template_builtins.ttags) != -1) { var fragment = tagname.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>"); } }); // Filters are functions, class '.nf' $("div.highlight\\-html\\+django span.nf").each(function(i, elem) { var filtername = $(elem).text(); if ($.inArray(filtername, django_template_builtins.tfilters) != -1) { var fragment = filtername.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>"); } }); }); })(jQuery); </script> </head> <body role="document"> <div class="document"> <div id="custom-doc" class="yui-t6"> <div id="hd"> <h1><a href="../../index.html">Django 1.8.19 documentation</a></h1> <div id="global-nav"> <a title="Home page" href="../../index.html">Home</a> | <a title="Table of contents" href="../../contents.html">Table of contents</a> | <a title="Global index" href="../../genindex.html">Index</a> | <a title="Module index" href="../../py-modindex.html">Modules</a> </div> <div class="nav"> « <a href="generic-views.html" title="Generic views">previous</a> | <a href="../index.html" title="Using Django" accesskey="U">up</a> | <a href="sessions.html" title="How to use sessions">next</a> »</div> </div> <div id="bd"> <div id="yui-main"> <div class="yui-b"> <div class="yui-g" id="topics-http-middleware"> <div class="section" id="s-middleware"> <span id="middleware"></span><h1>Middleware<a class="headerlink" href="#middleware" title="Permalink to this headline">¶</a></h1> <p>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 or output.</p> <p>Each middleware component is responsible for doing some specific function. For example, Django includes a middleware component, <a class="reference internal" href="../../ref/middleware.html#django.contrib.auth.middleware.AuthenticationMiddleware" title="django.contrib.auth.middleware.AuthenticationMiddleware"><code class="xref py py-class docutils literal"><span class="pre">AuthenticationMiddleware</span></code></a>, that associates users with requests using sessions.</p> <p>This document explains how middleware works, how you activate middleware, and how to write your own middleware. Django ships with some built-in middleware you can use right out of the box. They’re documented in the <a class="reference internal" href="../../ref/middleware.html"><span class="doc">built-in middleware reference</span></a>.</p> <div class="section" id="s-activating-middleware"> <span id="activating-middleware"></span><h2>Activating middleware<a class="headerlink" href="#activating-middleware" title="Permalink to this headline">¶</a></h2> <p>To activate a middleware component, add it to the <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><code class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></code></a> tuple in your Django settings.</p> <p>In <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><code class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></code></a>, each middleware component is represented by a string: the full Python path to the middleware’s class name. For example, here’s the default value created by <a class="reference internal" href="../../ref/django-admin.html#django-admin-startproject"><code class="xref std std-djadmin docutils literal"><span class="pre">django-admin</span> <span class="pre">startproject</span></code></a>:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">MIDDLEWARE_CLASSES</span> <span class="o">=</span> <span class="p">(</span> <span class="s1">'django.middleware.security.SecurityMiddleware'</span><span class="p">,</span> <span class="s1">'django.contrib.sessions.middleware.SessionMiddleware'</span><span class="p">,</span> <span class="s1">'django.middleware.common.CommonMiddleware'</span><span class="p">,</span> <span class="s1">'django.middleware.csrf.CsrfViewMiddleware'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.middleware.AuthenticationMiddleware'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.middleware.SessionAuthenticationMiddleware'</span><span class="p">,</span> <span class="s1">'django.contrib.messages.middleware.MessageMiddleware'</span><span class="p">,</span> <span class="s1">'django.middleware.clickjacking.XFrameOptionsMiddleware'</span><span class="p">,</span> <span class="p">)</span> </pre></div> </div> <p>A Django installation doesn’t require any middleware — <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><code class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></code></a> can be empty, if you’d like — but it’s strongly suggested that you at least use <a class="reference internal" href="../../ref/middleware.html#django.middleware.common.CommonMiddleware" title="django.middleware.common.CommonMiddleware"><code class="xref py py-class docutils literal"><span class="pre">CommonMiddleware</span></code></a>.</p> <p>The order in <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><code class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></code></a> matters because a middleware can depend on other middleware. For instance, <a class="reference internal" href="../../ref/middleware.html#django.contrib.auth.middleware.AuthenticationMiddleware" title="django.contrib.auth.middleware.AuthenticationMiddleware"><code class="xref py py-class docutils literal"><span class="pre">AuthenticationMiddleware</span></code></a> stores the authenticated user in the session; therefore, it must run after <a class="reference internal" href="../../ref/middleware.html#django.contrib.sessions.middleware.SessionMiddleware" title="django.contrib.sessions.middleware.SessionMiddleware"><code class="xref py py-class docutils literal"><span class="pre">SessionMiddleware</span></code></a>. See <a class="reference internal" href="../../ref/middleware.html#middleware-ordering"><span class="std std-ref">Middleware ordering</span></a> for some common hints about ordering of Django middleware classes.</p> </div> <div class="section" id="s-hooks-and-application-order"> <span id="hooks-and-application-order"></span><h2>Hooks and application order<a class="headerlink" href="#hooks-and-application-order" title="Permalink to this headline">¶</a></h2> <p>During the request phase, before calling the view, Django applies middleware in the order it’s defined in <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><code class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></code></a>, top-down. Two hooks are available:</p> <ul class="simple"> <li><a class="reference internal" href="#process_request" title="process_request"><code class="xref py py-meth docutils literal"><span class="pre">process_request()</span></code></a></li> <li><a class="reference internal" href="#process_view" title="process_view"><code class="xref py py-meth docutils literal"><span class="pre">process_view()</span></code></a></li> </ul> <p>During the response phase, after calling the view, middleware are applied in reverse order, from the bottom up. Three hooks are available:</p> <ul class="simple"> <li><a class="reference internal" href="#process_exception" title="process_exception"><code class="xref py py-meth docutils literal"><span class="pre">process_exception()</span></code></a> (only if the view raised an exception)</li> <li><a class="reference internal" href="#process_template_response" title="process_template_response"><code class="xref py py-meth docutils literal"><span class="pre">process_template_response()</span></code></a> (only for template responses)</li> <li><a class="reference internal" href="#process_response" title="process_response"><code class="xref py py-meth docutils literal"><span class="pre">process_response()</span></code></a></li> </ul> <a class="reference internal image-reference" href="../../_images/middleware.svg"><img alt="middleware application order" height="409" src="../../_images/middleware.svg" width="481" /></a> <p>If you prefer, you can also think of it like an onion: each middleware class is a “layer” that wraps the view.</p> <p>The behavior of each hook is described below.</p> </div> <div class="section" id="s-writing-your-own-middleware"> <span id="writing-your-own-middleware"></span><h2>Writing your own middleware<a class="headerlink" href="#writing-your-own-middleware" title="Permalink to this headline">¶</a></h2> <p>Writing your own middleware is easy. Each middleware component is a single Python class that defines one or more of the following methods:</p> <div class="section" id="s-process-request"> <span id="s-request-middleware"></span><span id="process-request"></span><span id="request-middleware"></span><h3><code class="docutils literal"><span class="pre">process_request</span></code><a class="headerlink" href="#process-request" title="Permalink to this headline">¶</a></h3> <dl class="method"> <dt id="process_request"> <code class="descname">process_request</code>(<em>request</em>)<a class="headerlink" href="#process_request" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p><code class="docutils literal"><span class="pre">request</span></code> is an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> object.</p> <p><code class="docutils literal"><span class="pre">process_request()</span></code> is called on each request, before Django decides which view to execute.</p> <p>It should return either <code class="docutils literal"><span class="pre">None</span></code> or an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> object. If it returns <code class="docutils literal"><span class="pre">None</span></code>, Django will continue processing this request, executing any other <code class="docutils literal"><span class="pre">process_request()</span></code> middleware, then, <code class="docutils literal"><span class="pre">process_view()</span></code> middleware, and finally, the appropriate view. If it returns an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> object, Django won’t bother calling any other request, view or exception middleware, or the appropriate view; it’ll apply response middleware to that <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a>, and return the result.</p> </div> <div class="section" id="s-process-view"> <span id="s-view-middleware"></span><span id="process-view"></span><span id="view-middleware"></span><h3><code class="docutils literal"><span class="pre">process_view</span></code><a class="headerlink" href="#process-view" title="Permalink to this headline">¶</a></h3> <dl class="method"> <dt id="process_view"> <code class="descname">process_view</code>(<em>request</em>, <em>view_func</em>, <em>view_args</em>, <em>view_kwargs</em>)<a class="headerlink" href="#process_view" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p><code class="docutils literal"><span class="pre">request</span></code> is an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> object. <code class="docutils literal"><span class="pre">view_func</span></code> is the Python function that Django is about to use. (It’s the actual function object, not the name of the function as a string.) <code class="docutils literal"><span class="pre">view_args</span></code> is a list of positional arguments that will be passed to the view, and <code class="docutils literal"><span class="pre">view_kwargs</span></code> is a dictionary of keyword arguments that will be passed to the view. Neither <code class="docutils literal"><span class="pre">view_args</span></code> nor <code class="docutils literal"><span class="pre">view_kwargs</span></code> include the first view argument (<code class="docutils literal"><span class="pre">request</span></code>).</p> <p><code class="docutils literal"><span class="pre">process_view()</span></code> is called just before Django calls the view.</p> <p>It should return either <code class="docutils literal"><span class="pre">None</span></code> or an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> object. If it returns <code class="docutils literal"><span class="pre">None</span></code>, Django will continue processing this request, executing any other <code class="docutils literal"><span class="pre">process_view()</span></code> middleware and, then, the appropriate view. If it returns an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> object, Django won’t bother calling any other view or exception middleware, or the appropriate view; it’ll apply response middleware to that <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a>, and return the result.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>Accessing <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest.POST" title="django.http.HttpRequest.POST"><code class="xref py py-attr docutils literal"><span class="pre">request.POST</span></code></a> or <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest.REQUEST" title="django.http.HttpRequest.REQUEST"><code class="xref py py-attr docutils literal"><span class="pre">request.REQUEST</span></code></a> inside middleware from <code class="docutils literal"><span class="pre">process_request</span></code> or <code class="docutils literal"><span class="pre">process_view</span></code> will prevent any view running after the middleware from being able to <a class="reference internal" href="file-uploads.html#modifying-upload-handlers-on-the-fly"><span class="std std-ref">modify the upload handlers for the request</span></a>, and should normally be avoided.</p> <p class="last">The <a class="reference internal" href="../../ref/middleware.html#django.middleware.csrf.CsrfViewMiddleware" title="django.middleware.csrf.CsrfViewMiddleware"><code class="xref py py-class docutils literal"><span class="pre">CsrfViewMiddleware</span></code></a> class can be considered an exception, as it provides the <a class="reference internal" href="../../ref/csrf.html#django.views.decorators.csrf.csrf_exempt" title="django.views.decorators.csrf.csrf_exempt"><code class="xref py py-func docutils literal"><span class="pre">csrf_exempt()</span></code></a> and <a class="reference internal" href="../../ref/csrf.html#django.views.decorators.csrf.csrf_protect" title="django.views.decorators.csrf.csrf_protect"><code class="xref py py-func docutils literal"><span class="pre">csrf_protect()</span></code></a> decorators which allow views to explicitly control at what point the CSRF validation should occur.</p> </div> </div> <div class="section" id="s-process-template-response"> <span id="s-template-response-middleware"></span><span id="process-template-response"></span><span id="template-response-middleware"></span><h3><code class="docutils literal"><span class="pre">process_template_response</span></code><a class="headerlink" href="#process-template-response" title="Permalink to this headline">¶</a></h3> <dl class="method"> <dt id="process_template_response"> <code class="descname">process_template_response</code>(<em>request</em>, <em>response</em>)<a class="headerlink" href="#process_template_response" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p><code class="docutils literal"><span class="pre">request</span></code> is an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> object. <code class="docutils literal"><span class="pre">response</span></code> is the <a class="reference internal" href="../../ref/template-response.html#django.template.response.TemplateResponse" title="django.template.response.TemplateResponse"><code class="xref py py-class docutils literal"><span class="pre">TemplateResponse</span></code></a> object (or equivalent) returned by a Django view or by a middleware.</p> <p><code class="docutils literal"><span class="pre">process_template_response()</span></code> is called just after the view has finished executing, if the response instance has a <code class="docutils literal"><span class="pre">render()</span></code> method, indicating that it is a <a class="reference internal" href="../../ref/template-response.html#django.template.response.TemplateResponse" title="django.template.response.TemplateResponse"><code class="xref py py-class docutils literal"><span class="pre">TemplateResponse</span></code></a> or equivalent.</p> <p>It must return a response object that implements a <code class="docutils literal"><span class="pre">render</span></code> method. It could alter the given <code class="docutils literal"><span class="pre">response</span></code> by changing <code class="docutils literal"><span class="pre">response.template_name</span></code> and <code class="docutils literal"><span class="pre">response.context_data</span></code>, or it could create and return a brand-new <a class="reference internal" href="../../ref/template-response.html#django.template.response.TemplateResponse" title="django.template.response.TemplateResponse"><code class="xref py py-class docutils literal"><span class="pre">TemplateResponse</span></code></a> or equivalent.</p> <p>You don’t need to explicitly render responses – responses will be automatically rendered once all template response middleware has been called.</p> <p>Middleware are run in reverse order during the response phase, which includes <code class="docutils literal"><span class="pre">process_template_response()</span></code>.</p> </div> <div class="section" id="s-process-response"> <span id="s-response-middleware"></span><span id="process-response"></span><span id="response-middleware"></span><h3><code class="docutils literal"><span class="pre">process_response</span></code><a class="headerlink" href="#process-response" title="Permalink to this headline">¶</a></h3> <dl class="method"> <dt id="process_response"> <code class="descname">process_response</code>(<em>request</em>, <em>response</em>)<a class="headerlink" href="#process_response" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p><code class="docutils literal"><span class="pre">request</span></code> is an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> object. <code class="docutils literal"><span class="pre">response</span></code> is the <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> or <a class="reference internal" href="../../ref/request-response.html#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><code class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></code></a> object returned by a Django view or by a middleware.</p> <p><code class="docutils literal"><span class="pre">process_response()</span></code> is called on all responses before they’re returned to the browser.</p> <p>It must return an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> or <a class="reference internal" href="../../ref/request-response.html#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><code class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></code></a> object. It could alter the given <code class="docutils literal"><span class="pre">response</span></code>, or it could create and return a brand-new <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> or <a class="reference internal" href="../../ref/request-response.html#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><code class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></code></a>.</p> <p>Unlike the <code class="docutils literal"><span class="pre">process_request()</span></code> and <code class="docutils literal"><span class="pre">process_view()</span></code> methods, the <code class="docutils literal"><span class="pre">process_response()</span></code> method is always called, even if the <code class="docutils literal"><span class="pre">process_request()</span></code> and <code class="docutils literal"><span class="pre">process_view()</span></code> methods of the same middleware class were skipped (because an earlier middleware method returned an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a>). In particular, this means that your <code class="docutils literal"><span class="pre">process_response()</span></code> method cannot rely on setup done in <code class="docutils literal"><span class="pre">process_request()</span></code>.</p> <p>Finally, remember that during the response phase, middleware are applied in reverse order, from the bottom up. This means classes defined at the end of <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><code class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></code></a> will be run first.</p> <div class="section" id="s-dealing-with-streaming-responses"> <span id="dealing-with-streaming-responses"></span><h4>Dealing with streaming responses<a class="headerlink" href="#dealing-with-streaming-responses" title="Permalink to this headline">¶</a></h4> <p>Unlike <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a>, <a class="reference internal" href="../../ref/request-response.html#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><code class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></code></a> does not have a <code class="docutils literal"><span class="pre">content</span></code> attribute. As a result, middleware can no longer assume that all responses will have a <code class="docutils literal"><span class="pre">content</span></code> attribute. If they need access to the content, they must test for streaming responses and adjust their behavior accordingly:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">response</span><span class="o">.</span><span class="n">streaming</span><span class="p">:</span> <span class="n">response</span><span class="o">.</span><span class="n">streaming_content</span> <span class="o">=</span> <span class="n">wrap_streaming_content</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">streaming_content</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="n">response</span><span class="o">.</span><span class="n">content</span> <span class="o">=</span> <span class="n">alter_content</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">content</span><span class="p">)</span> </pre></div> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p><code class="docutils literal"><span class="pre">streaming_content</span></code> should be assumed to be too large to hold in memory. Response middleware may wrap it in a new generator, but must not consume it. Wrapping is typically implemented as follows:</p> <div class="last highlight-default"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">wrap_streaming_content</span><span class="p">(</span><span class="n">content</span><span class="p">):</span> <span class="k">for</span> <span class="n">chunk</span> <span class="ow">in</span> <span class="n">content</span><span class="p">:</span> <span class="k">yield</span> <span class="n">alter_content</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span> </pre></div> </div> </div> </div> </div> <div class="section" id="s-process-exception"> <span id="s-exception-middleware"></span><span id="process-exception"></span><span id="exception-middleware"></span><h3><code class="docutils literal"><span class="pre">process_exception</span></code><a class="headerlink" href="#process-exception" title="Permalink to this headline">¶</a></h3> <dl class="method"> <dt id="process_exception"> <code class="descname">process_exception</code>(<em>request</em>, <em>exception</em>)<a class="headerlink" href="#process_exception" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p><code class="docutils literal"><span class="pre">request</span></code> is an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> object. <code class="docutils literal"><span class="pre">exception</span></code> is an <code class="docutils literal"><span class="pre">Exception</span></code> object raised by the view function.</p> <p>Django calls <code class="docutils literal"><span class="pre">process_exception()</span></code> when a view raises an exception. <code class="docutils literal"><span class="pre">process_exception()</span></code> should return either <code class="docutils literal"><span class="pre">None</span></code> or an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> object. If it returns an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> object, the template response and response middleware will be applied, and the resulting response returned to the browser. Otherwise, default exception handling kicks in.</p> <p>Again, middleware are run in reverse order during the response phase, which includes <code class="docutils literal"><span class="pre">process_exception</span></code>. If an exception middleware returns a response, the middleware classes above that middleware will not be called at all.</p> </div> <div class="section" id="s-init"> <span id="init"></span><h3><code class="docutils literal"><span class="pre">__init__</span></code><a class="headerlink" href="#init" title="Permalink to this headline">¶</a></h3> <p>Most middleware classes won’t need an initializer since middleware classes are essentially placeholders for the <code class="docutils literal"><span class="pre">process_*</span></code> methods. If you do need some global state you may use <code class="docutils literal"><span class="pre">__init__</span></code> to set up. However, keep in mind a couple of caveats:</p> <ul class="simple"> <li>Django initializes your middleware without any arguments, so you can’t define <code class="docutils literal"><span class="pre">__init__</span></code> as requiring any arguments.</li> <li>Unlike the <code class="docutils literal"><span class="pre">process_*</span></code> methods which get called once per request, <code class="docutils literal"><span class="pre">__init__</span></code> gets called only <em>once</em>, when the Web server responds to the first request.</li> </ul> <div class="section" id="s-marking-middleware-as-unused"> <span id="marking-middleware-as-unused"></span><h4>Marking middleware as unused<a class="headerlink" href="#marking-middleware-as-unused" title="Permalink to this headline">¶</a></h4> <p>It’s sometimes useful to determine at run-time whether a piece of middleware should be used. In these cases, your middleware’s <code class="docutils literal"><span class="pre">__init__</span></code> method may raise <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.MiddlewareNotUsed" title="django.core.exceptions.MiddlewareNotUsed"><code class="xref py py-exc docutils literal"><span class="pre">django.core.exceptions.MiddlewareNotUsed</span></code></a>. Django will then remove that piece of middleware from the middleware process and a debug message will be logged to the <code class="docutils literal"><span class="pre">django.request</span></code> logger when <a class="reference internal" href="../../ref/settings.html#std:setting-DEBUG"><code class="xref std std-setting docutils literal"><span class="pre">DEBUG</span></code></a> is set to <code class="docutils literal"><span class="pre">True</span></code>.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.8:</span> <p>Previously, <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.MiddlewareNotUsed" title="django.core.exceptions.MiddlewareNotUsed"><code class="xref py py-exc docutils literal"><span class="pre">MiddlewareNotUsed</span></code></a> exceptions weren’t logged.</p> </div> </div> </div> <div class="section" id="s-guidelines"> <span id="guidelines"></span><h3>Guidelines<a class="headerlink" href="#guidelines" title="Permalink to this headline">¶</a></h3> <ul class="simple"> <li>Middleware classes don’t have to subclass anything.</li> <li>The middleware class can live anywhere on your Python path. All Django cares about is that the <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><code class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></code></a> setting includes the path to it.</li> <li>Feel free to look at <a class="reference internal" href="../../ref/middleware.html"><span class="doc">Django’s available middleware</span></a> for examples.</li> <li>If you write a middleware component that you think would be useful to other people, contribute to the community! <a class="reference internal" href="../../internals/contributing/index.html"><span class="doc">Let us know</span></a>, and we’ll consider adding it to Django.</li> </ul> </div> </div> </div> </div> </div> </div> <div class="yui-b" id="sidebar"> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h3><a href="../../contents.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">Middleware</a><ul> <li><a class="reference internal" href="#activating-middleware">Activating middleware</a></li> <li><a class="reference internal" href="#hooks-and-application-order">Hooks and application order</a></li> <li><a class="reference internal" href="#writing-your-own-middleware">Writing your own middleware</a><ul> <li><a class="reference internal" href="#process-request"><code class="docutils literal"><span class="pre">process_request</span></code></a></li> <li><a class="reference internal" href="#process-view"><code class="docutils literal"><span class="pre">process_view</span></code></a></li> <li><a class="reference internal" href="#process-template-response"><code class="docutils literal"><span class="pre">process_template_response</span></code></a></li> <li><a class="reference internal" href="#process-response"><code class="docutils literal"><span class="pre">process_response</span></code></a><ul> <li><a class="reference internal" href="#dealing-with-streaming-responses">Dealing with streaming responses</a></li> </ul> </li> <li><a class="reference internal" href="#process-exception"><code class="docutils literal"><span class="pre">process_exception</span></code></a></li> <li><a class="reference internal" href="#init"><code class="docutils literal"><span class="pre">__init__</span></code></a><ul> <li><a class="reference internal" href="#marking-middleware-as-unused">Marking middleware as unused</a></li> </ul> </li> <li><a class="reference internal" href="#guidelines">Guidelines</a></li> </ul> </li> </ul> </li> </ul> <h3>Browse</h3> <ul> <li>Prev: <a href="generic-views.html">Generic views</a></li> <li>Next: <a href="sessions.html">How to use sessions</a></li> </ul> <h3>You are here:</h3> <ul> <li> <a href="../../index.html">Django 1.8.19 documentation</a> <ul><li><a href="../index.html">Using Django</a> <ul><li><a href="index.html">Handling HTTP requests</a> <ul><li>Middleware</li></ul> </li></ul></li></ul> </li> </ul> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../../_sources/topics/http/middleware.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="../../search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <h3>Last update:</h3> <p class="topless">Mar 10, 2018</p> </div> </div> <div id="ft"> <div class="nav"> « <a href="generic-views.html" title="Generic views">previous</a> | <a href="../index.html" title="Using Django" accesskey="U">up</a> | <a href="sessions.html" title="How to use sessions">next</a> »</div> </div> </div> <div class="clearer"></div> </div> </body> </html>