Skip to content
Myr

deferredcallbacks.rst

This file

Path

docs/patterns/deferredcallbacks.rst

44 lines · 1.8 KiB

Last changed by

Not known.

History of this file

Take it

1Deferred Request Callbacks2==========================34One of the design principles of Flask is that response objects are created and5passed down a chain of potential callbacks that can modify them or replace6them. When the request handling starts, there is no response object yet. It is7created as necessary either by a view function or by some other component in8the system.910What happens if you want to modify the response at a point where the response11does not exist yet?  A common example for that would be a12:meth:`~flask.Flask.before_request` callback that wants to set a cookie on the13response object.1415One way is to avoid the situation. Very often that is possible. For instance16you can try to move that logic into a :meth:`~flask.Flask.after_request`17callback instead. However, sometimes moving code there makes it18more complicated or awkward to reason about.1920As an alternative, you can use :func:`~flask.after_this_request` to register21callbacks that will execute after only the current request. This way you can22defer code execution from anywhere in the application, based on the current23request.2425At any time during a request, we can register a function to be called at the26end of the request. For example you can remember the current language of the27user in a cookie in a :meth:`~flask.Flask.before_request` callback::2829    from flask import request, after_this_request3031    @app.before_request32    def detect_user_language():33        language = request.cookies.get('user_lang')3435        if language is None:36            language = guess_language_from_request()3738            # when the response exists, set a cookie with the language39            @after_this_request40            def remember_language(response):41                response.set_cookie('user_lang', language)42                return response4344        g.language = language