1. Before each request, before_request() functions are executed. If one of these
functions return a response, the other functions are no longer called. In any case
however the return value is treated as a replacement for the view’s return value.
2. If the before_request() functions did not return a response, the regular request
handling kicks in and the view function that was matched has the chance to
return a response.
3. The return value of the view is then converted into an actual response object and
handed over to the after_request() functions which have the chance to replace
it or modify it in place.
4. At the end of the request the teardown_request() functions are executed. This
always happens, even in case of an unhandled exception down the road or if a
before-request handler was not executed yet or at all (for example in test envi-
ronments sometimes you might want to not execute before-request callbacks).
Now what happens on errors? In production mode if an exception is not caught, the
500 internal server handler is called. In development mode however the exception is
not further processed and bubbles up to the WSGI server. That way things like the
interactive debugger can provide helpful debug information.
An important change in 0.7 is that the internal server error is now no longer post
processed by the after request callbacks and after request callbacks are no longer guar-
anteed to be executed. This way the internal dispatching code looks cleaner and is
easier to customize and understand.
The new teardown functions are supposed to be used as a replacement for things that
absolutely need to happen at the end of request.
14.4 Teardown Callbacks
The teardown callbacks are special callbacks in that they are executed at at different
point. Strictly speaking they are independent of the actual request handling as they
are bound to the lifecycle of the RequestContext object. When the request context is
popped, the teardown_request() functions are called.
This is important to know if the life of the request context is prolonged by using the
test client in a with statement or when using the request context from the command
with app.test_client() as client:
resp = client.get(/foo)
# the teardown functions are still not called at that point
# even though the response ended and you have the response
# object in your hand
# only when the code reaches this point the teardown functions
# are called. Alternatively the same thing happens if another
# request was triggered from the test client