How to access the current response's status_code in Flask's teardown_request?
<p>I'm interfacing with an internal logging system and I'd like to obtain the current response's <code>status_code</code> from within Flask's <code>teardown_request</code> callback: <a href="http://flask.pocoo.org/docs/0.11/api/#flask.Flask.teardown_request" rel="nofollow">http://flask.pocoo.org/docs/0.11/api/#flask.Flask.teardown_request</a>. I like that it is guaranteed to be called and I can get all the other information needed for my purposes.</p>

<p>I can access the current response and it's <code>status_code</code> if I connect to the <code>request_finished</code> signal:</p>

<pre><code>def request_finished_listener(sender, response):
    print(response.status_code)

request_finished.connect(request_finished_listener)
</code></pre>

<p>But I'd like to do all my data collection within the <code>teardown_request</code> if possible.</p>

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

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

python flask