Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I log request POST body in Flask?

I'm using flask server, and I want to log each request data and header (so I can use it afterwards to test my server). I took the werkzeug logger with

    self._app.log = logging.getLogger('werkzeug')     self._app.log.addHandler(RotatingFileHandler('log.txt', mode='w'))     self._app.log.setLevel(logging.DEBUG) 

But I don't understand how to change the log format to include request.data and request.headers, all I have is the default log

    127.0.0.1 - - [17/Feb/2015 17:09:43] "POST /helloworld HTTP/1.1" 200 - 
like image 733
eplaut Avatar asked Jul 26 '15 13:07

eplaut


People also ask

How do I get a POST request in Flask?

Inside the view function, you will need to check if the request method is GET or POST. If it is a GET request, you can display the form. Otherwise, if it is a POST request, then you will want to process the incoming data. Fill out the language field with value of Python and the framework field with the value of Flask .

How do I get post json data in Flask?

You need to set the request content type to application/json for the . json property and . get_json() method (with no arguments) to work as either will produce None otherwise.

How do I check my POST method in Flask?

In order to demonstrate the use of POST method in URL routing, first let us create an HTML form and use the POST method to send form data to a URL. Now enter the following script in Python shell. After the development server starts running, open login. html in the browser, enter name in the text field and click Submit.


1 Answers

You can log additional info for each request with a Flask.before_request hook:

@app.before_request def log_request_info():     app.logger.debug('Headers: %s', request.headers)     app.logger.debug('Body: %s', request.get_data()) 
like image 133
Martijn Pieters Avatar answered Oct 07 '22 17:10

Martijn Pieters