Deferred Request Callbacks
One of the design principles of Flask is that response objects are created andpassed down a chain of potential callbacks that can modify them or replacethem. When the request handling starts, there is no response object yet. It iscreated as necessary either by a view function or by some other component inthe system.
What happens if you want to modify the response at a point where the responsedoes not exist yet? A common example for that would be abefore_request() callback that wants to set a cookie on theresponse object.
One way is to avoid the situation. Very often that is possible. For instanceyou can try to move that logic into a after_request()callback instead. However, sometimes moving code there makes it moremore complicated or awkward to reason about.
As an alternative, you can use after_this_request() to registercallbacks that will execute after only the current request. This way you candefer code execution from anywhere in the application, based on the currentrequest.
At any time during a request, we can register a function to be called at theend of the request. For example you can remember the current language of theuser in a cookie in a before_request() callback:
1. from flask import request, after_this_request
3. @app.before_request
4. def detect_user_language():
5. language = request.cookies.get('user_lang')
7. if language is None:
8. language = guess_language_from_request()
10. # when the response exists, set a cookie with the language
11. @after_this_request
12. def remember_language(response):
13. response.set_cookie('user_lang', language)
14. return response
16. g.language = language
