I am debugging a microcontroller I've built which is writing raw HTTP requests line by line. I am using Flask for my backend and I would like to see the entire request as it appears in this format:
GET / HTTP/1.1 Content-length: 123 User-agent: blah ...
I know Flask is based on WSGI. Is there anyway to get this to work with Flask?
Use request. get_data() to get the raw data, regardless of content type. The data is cached and you can subsequently access request.
Flask is a WSGI application. A WSGI server is used to run the application, converting incoming HTTP requests to the standard WSGI environ, and converting outgoing WSGI responses to HTTP responses.
Flask has different decorators to handle http requests. Http protocol is the basis for data communication in the World Wide Web. Used to send HTML form data to the server. The data received by the POST method is not cached by the server.
Flask does not route print to the response. If you are running the development server from a terminal session, you will see the output there. If you are running it through a WSGI server such as uWSGI, the output will appear in the logs instead.
Yes, Flask is a WSGI application, so it is trivial to wrap your app in an extra layer that logs the request:
import pprint class LoggingMiddleware(object): def __init__(self, app): self._app = app def __call__(self, env, resp): errorlog = env['wsgi.errors'] pprint.pprint(('REQUEST', env), stream=errorlog) def log_response(status, headers, *args): pprint.pprint(('RESPONSE', status, headers), stream=errorlog) return resp(status, headers, *args) return self._app(env, log_response)
This defines a piece of middleware to wrap your Flask application in. The advantage is that it operates entirely independent of Flask, giving you unfiltered insight into what goes in and what comes out.
How you apply the middleware depends on the exact WSGI server you are using; see your WSGI server documentation.
When running Flask with the built-in server (app.run()
), do:
if __name__ == '__main__': app.wsgi_app = LoggingMiddleware(app.wsgi_app) app.run()
The little app.wsgi_app
wrapping dance places the LoggingMiddleware
around the Flask WSGI application.
The output goes to the wsgi.error
stream; where that ends up again depends on your WSGI server; mod_wsgi
puts this in the Apache error log for your site, the bundled Flask server prints this to stderr
.
With flask you have access to the request object which contains all the HTTP details:
from flask import request @app.route('/') def index(): print(request.headers)
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