I have two after_request handlers. In my case, I need one to fire before the next.
@app.after_request
def after_request_check_something(response):
# do something
return response
@app.after_request
def after_request_compress(response):
# do something
return response
In my case, I want compress to go first, then check_something. But they are firing in reverse.
If it matters, in my actual code, these two handlers are not consecutively declared like this. They are each in different modules that are installed at different times.
How can I control the order of execution?
Handlers are executed in the order they are defined in the handlers section, not in the order listed in the notify statement. Notifying the same handler multiple times will result in executing the handler only once regardless of how many tasks notify it.
By default, handlers run after all the tasks in a particular play have been completed. Notified handlers are executed automatically after each of the following sections, in the following order: pre_tasks, roles / tasks and post_tasks. This approach is efficient, because the handler only runs once, regardless of how many tasks notify it.
Console Control Handlers. Each console process has its own list of control handler functions that are called by the system when the process receives a CTRL+C, CTRL+BREAK, or CTRL+CLOSE signal. Initially, the list of control handlers for each process contains only a default handler function that calls the ExitProcess function.
If none of the handlers returns TRUE, the default handler is called. The function's dwCtrlType parameter identifies which control signal was received, and the return value indicates whether the signal was handled.
Flask's after_request
hooks are indeed executed in the reversed order of their declaration. Conversely, before_request
hooks are executed in the order of their declaration.
If after_request
hooks are declared on a blueprint, those are executed in reversed declaration order, before global after_request
hooks. If before_request
hooks are declared on a blueprint, those are executed in declaration order, after global before_request
hooks.
See preprocess_request and process_response source code for implementation details.
Edit: user8808265's answer looks more correct than mine.
From the documentation, it does not appear that the execution of these after_request
handlers can be ordered. The implementation has the handlers stored in a dictionary which is inherently unordered.
I suggest making a separate handler that calls both in the correct order, something like:
def after_request_check_something(response):
# do something
return response
def after_request_compress(response):
# do something
return response
@app.after_request
def after_request_combined(response):
response1 = after_request_compress(response)
return after_request_check_something(response1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With