Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get status code when using after_request?

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

like image 651
DavidK Avatar asked Feb 15 '16 13:02

DavidK


People also ask

How do I get my flask 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.

Are HTTP status codes integers?

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.


1 Answers

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
like image 116
Ioannis Lalopoulos Avatar answered Sep 20 '22 06:09

Ioannis Lalopoulos