Skip to content
Myr

deferredcallbacks.rst

This file

Path

docs/patterns/deferredcallbacks.rst

73 lines · 2.5 KiB

Last changed by

Not known.

History of this file

Take it

1.. _deferred-callbacks:23Deferred Request Callbacks4==========================56One of the design principles of Flask is that response objects are created7and passed down a chain of potential callbacks that can modify them or8replace them.  When the request handling starts, there is no response9object yet.  It is created as necessary either by a view function or by10some other component in the system.1112But what happens if you want to modify the response at a point where the13response does not exist yet?  A common example for that would be a14before-request function that wants to set a cookie on the response object.1516One way is to avoid the situation.  Very often that is possible.  For17instance you can try to move that logic into an after-request callback18instead.  Sometimes however moving that code there is just not a very19pleasant experience or makes code look very awkward.2021As an alternative possibility you can attach a bunch of callback functions22to the :data:`~flask.g` object and call them at the end of the request.23This way you can defer code execution from anywhere in the application.242526The Decorator27-------------2829The following decorator is the key.  It registers a function on a list on30the :data:`~flask.g` object::3132    from flask import g3334    def after_this_request(f):35        if not hasattr(g, 'after_request_callbacks'):36            g.after_request_callbacks = []37        g.after_request_callbacks.append(f)38        return f394041Calling the Deferred42--------------------4344Now you can use the `after_this_request` decorator to mark a function to45be called at the end of the request.  But we still need to call them.  For46this the following function needs to be registered as47:meth:`~flask.Flask.after_request` callback::4849    @app.after_request50    def call_after_request_callbacks(response):51        for callback in getattr(g, 'after_request_callbacks', ()):52            callback(response)53        return response545556A Practical Example57-------------------5859At any time during a request, we can register a function to be called at the60end of the request.  For example you can remember the current language of the61user in a cookie in the before-request function::6263    from flask import request6465    @app.before_request66    def detect_user_language():67        language = request.cookies.get('user_lang')68        if language is None:69            language = guess_language_from_request()70            @after_this_request71            def remember_language(response):72                response.set_cookie('user_lang', language)73        g.language = language