saschwarz saschwarz - 10 months ago 55
Python Question

How to access the current response's status_code in Flask's teardown_request?

I'm interfacing with an internal logging system and I'd like to obtain the current response's

from within Flask's
callback: I like that it is guaranteed to be called and I can get all the other information needed for my purposes.

I can access the current response and it's
if I connect to the

def request_finished_listener(sender, response):


But I'd like to do all my data collection within the
if possible.

Answer Source

You can't. teardown_request is called as cleanup after the response is generated, it does not have access to the response. You should use the request_finished signal or after_request decorator if you need access to the response from within Flask. teardown_request is only intended for cleaning up resources.

If you need to log something about the response and absolutely don't want to use request_finished or after_request, you'll have to wrap the Flask app in WSGI middleware.