Is there a way to print a request in flask as a string for debugging purposes? I'd simply like to print all params of a post request without having to write my own formatter for the request object.
Flask Debug mode allows developers to locate any possible error and as well the location of the error, by logging a traceback of the error. The Flask debug mode also enables developers to interactively run arbitrary python codes, so that one can resolve and get to the root cause on why an error happened.
To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things.
GET and POST requestsEnter the following script in the Python shell. Once the development server is up and running, open login. html in the browser, enter the name in the text field, and then click Submit. The form data will POST to the URL in the action clause of the form label.
You can use the pprint module.
Printing the request object itself won't show any useful information, however, so you will probably want to print the request.environ instead.
As an example:
from flask import Flask, Response, request
import pprint
app = Flask(__name__)
@app.route("/test")
def test():
str = pprint.pformat(request.environ, depth=5)
return Response(str, mimetype="text/text")
app.run(debug=True)
Yields:
{'CONTENT_LENGTH': '',
'CONTENT_TYPE': '',
'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch',
'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8,es;q=0.6',
'HTTP_CACHE_CONTROL': 'max-age=0',
'HTTP_CONNECTION': 'keep-alive',
'HTTP_COOKIE': 'session=eyJsYXN0X2FwcGlkIjoiMiI',
'HTTP_HOST': '127.0.0.1:5000',
'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36',
'PATH_INFO': '/test',
'QUERY_STRING': '',
'REMOTE_ADDR': '127.0.0.1',
'REMOTE_PORT': 36547,
'REQUEST_METHOD': 'GET',
'SCRIPT_NAME': '',
'SERVER_NAME': '127.0.0.1',
'SERVER_PORT': '5000',
'SERVER_PROTOCOL': 'HTTP/1.1',
'SERVER_SOFTWARE': 'Werkzeug/0.9.4',
'werkzeug.request': <Request 'http://127.0.0.1:5000/test' [GET]>,
'werkzeug.server.shutdown': <function shutdown_server at 0x10cd1b8>,
'wsgi.errors': <open file '<stderr>', mode 'w' at 0x7f5211b911e0>,
'wsgi.input': <socket._fileobject object at 0x1083f50>,
'wsgi.multiprocess': False,
'wsgi.multithread': False,
'wsgi.run_once': False,
'wsgi.url_scheme': 'http',
'wsgi.version': (1, 0)}
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