调试Python烧瓶中的请求/响应

时间:2016-03-18 05:00:48

标签: python flask

我是python2 flask&的新手我的任务是打印和打印保存整个HTTP请求和响应文件。我不太明白如何打印/检查请求对象,更不用说响应了。

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

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

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

任何提示?每个请求/响应应该是一个文件。

1 个答案:

答案 0 :(得分:11)

使用after_request

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

另外,要处理before_request

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

编辑:

response.get_data()可以获取响应数据。 response是响应的完整对象。它可以获取你想要的任何东西。

某些特定网址的更新(基于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)