<h1>Deferred Request Callbacks<aclass="headerlink"href="#deferred-request-callbacks"title="Link to this heading">¶</a></h1>
<p>One of the design principles of Flask is that response objects are created and
passed down a chain of potential callbacks that can modify them or replace
them. When the request handling starts, there is no response object yet. It is
created as necessary either by a view function or by some other component in
the system.</p>
<p>What happens if you want to modify the response at a point where the response
does not exist yet? A common example for that would be a
<aclass="reference internal"href="../api.html#flask.Flask.before_request"title="flask.Flask.before_request"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">before_request()</span></code></a> callback that wants to set a cookie on the
response object.</p>
<p>One way is to avoid the situation. Very often that is possible. For instance
you can try to move that logic into a <aclass="reference internal"href="../api.html#flask.Flask.after_request"title="flask.Flask.after_request"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">after_request()</span></code></a>
callback instead. However, sometimes moving code there makes it
more complicated or awkward to reason about.</p>
<p>As an alternative, you can use <aclass="reference internal"href="../api.html#flask.after_this_request"title="flask.after_this_request"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">after_this_request()</span></code></a> to register
callbacks that will execute after only the current request. This way you can
defer code execution from anywhere in the application, based on the current
request.</p>
<p>At any time during a request, we can register a function to be called at the
end of the request. For example you can remember the current language of the
user in a cookie in a <aclass="reference internal"href="../api.html#flask.Flask.before_request"title="flask.Flask.before_request"><codeclass="xref py py-meth docutils literal notranslate"><spanclass="pre">before_request()</span></code></a> callback:</p>