How to get the status code (200, 500, ... ) when using after_request ?
What I want is to have the kind of output we have with a logger (for example werkzeug) but where it's possible to add what I want (username, ...) :
remote_IP, timepoint, path, status_code
The make_response() method The make_response method from Flask returns a Response object that can be used to send custom headers and change the properties such as status_code, mimetype, and so on. We can set the status code using the make_response method in two ways: Pass the status code as a constructor parameter.
The Status-Code element in a server response, is a 3-digit integer where the first digit of the Status-Code defines the class of response and the last two digits do not have any categorization role. There are 5 values for the first digit: S.N. It means the request has been received and the process is continuing.
The function(s) that are registered to run after each request should take a response class object and return a response class object (see http://flask.pocoo.org/docs/0.10/api/#flask.Flask.after_request)
So you can take that info from the response class object, for more info on what is available see http://flask.pocoo.org/docs/0.10/api/#flask.Response
Here is a partial example:
import logging
#
# your other flask code here
#
@app.after_request
def log_the_status_code(response):
status_as_string = response.status
status_as_integer = response.status_code
logging.warning("status as string %s" % status_as_string)
logging.warning("status as integer %s" % status_as_integer)
return response
and as output, you should get in the console after a successful hit:
WARNING:root:status as string 200 OK
WARNING:root:status as integer 200
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