Debugging a request/response in Python flask

hendry

I am new to python2 flask & I am tasked to pretty print & save the entire HTTP request and response to file. I don't quite understand how to print/inspect the request object, let alone the response.

from flask import Flask, request
app = Flask(__name__)

@app.route('/')
def hi():
    print (request)
    return 'oh hai'

if __name__ == '__main__':
    app.run(debug=True)

Any tips? Each request/response should be one file.

Yanhui Zhou

Using after_request

@app.after_request
def after(response):
    # todo with response
    print(response.status)
    print(response.headers)
    print(response.get_data())
    return response

Also, to deal with request with before_request

@app.before_request
def before():
    # todo with request
    # e.g. print request.headers
    pass

Edit:

response.get_data() can get the data of response. And response is the whole object for response. It can fetch anything you want.

Update for some specific url (based on http://s.natalian.org/2016-03-19/foo.py):

    from __future__ import print_function
    from flask import Flask, request, g
    import time
    app = Flask(__name__)             

    @app.route('/')
    def hi():
        g.fn = str(time.time()) + ".txt"
        with open(g.fn,'w') as f:
            print ("Request headers", request.headers, file=f)            
        return 'oh hai'

    @app.route('/foo')
    def foo():
        return 'foo'

    @app.before_request
    def before():
        pass

    @app.after_request
    def after(response):
        fn = g.get('fn', None)
        if fn:
            with open(fn, 'a') as f:
                print("Printing response", file=f)
                print(response.status, file=f)
                print(response.headers, file=f)
                print(response.get_data(), file=f)
        return response

    if __name__ == '__main__':
        app.run(debug=True)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related