Skip to content
Myr

deferredcallbacks.rst

This file

Path

docs/patterns/deferredcallbacks.rst

46 lines · 1.8 KiB

Last changed by

Merge branch '1.0-maintenance'David Lordbefore adoptionf7d50d4

History of this file

Take it

1.. _deferred-callbacks:23Deferred Request Callbacks4==========================56One of the design principles of Flask is that response objects are created and7passed down a chain of potential callbacks that can modify them or replace8them. When the request handling starts, there is no response object yet. It is9created as necessary either by a view function or by some other component in10the system.1112What happens if you want to modify the response at a point where the response13does not exist yet?  A common example for that would be a14:meth:`~flask.Flask.before_request` callback that wants to set a cookie on the15response object.1617One way is to avoid the situation. Very often that is possible. For instance18you can try to move that logic into a :meth:`~flask.Flask.after_request`19callback instead. However, sometimes moving code there makes it more20more complicated or awkward to reason about.2122As an alternative, you can use :func:`~flask.after_this_request` to register23callbacks that will execute after only the current request. This way you can24defer code execution from anywhere in the application, based on the current25request.2627At any time during a request, we can register a function to be called at the28end of the request. For example you can remember the current language of the29user in a cookie in a :meth:`~flask.Flask.before_request` callback::3031    from flask import request, after_this_request3233    @app.before_request34    def detect_user_language():35        language = request.cookies.get('user_lang')3637        if language is None:38            language = guess_language_from_request()3940            # when the response exists, set a cookie with the language41            @after_this_request42            def remember_language(response):43                response.set_cookie('user_lang', language)44                return response4546        g.language = language