我在python中找到number simple个网络servers,它会启动快速服务器并简单地响应请求。我需要的是一个不会只打印每个请求的IP地址,时间戳,方法和响应代码的服务器(127.0.0.1 - - [28/Aug/2017 10:42:11] "POST / HTTP/1.1" 200 -
),而且,如果是POST请求,我需要它打印出来POST数据。
因此,例如,如果我在邮件正文中发送带有{"foo":"bar"}
的POST请求,我希望服务器在响应之前将127.0.0.1 - - [28/Aug/2017 10:42:11] "POST / HTTP/1.1" 200 - {"foo":"bar"}
打印到控制台。
我不确定如何修改上面的任何链接选项来执行此操作。如果有另一个简单的选项,那也可以。
答案 0 :(得分:1)
要打印出发送到服务器的任何JSON,请自己构建一个基本catch-all endpoint并从中打印JSON。在烧瓶中,这看起来如下:
import logging
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'], defaults={'path': ''})
@app.route('/<path:path>', methods=['POST', 'GET'])
def index(path):
print("HTTP {} to URL /{} received JSON {}".format(request.method, path, request.get_json()))
return "True"
这是我对服务器的调用:
In [15]: requests.post('http://localhost:5000/', json={'a': 1})
Out[15]: <Response [200]>
In [16]: requests.post('http://localhost:5000/some/endpoint', json={'a': 1})
Out[16]: <Response [200]>
In [17]: requests.get('http://localhost:5000/', json={'a': 1})
Out[17]: <Response [200]>
这是服务器输出:
In [7]: app.run(host='0.0.0.0')
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
HTTP POST to URL / received JSON {'a': 1}
127.0.0.1 - - [28/Aug/2017 11:57:49] "POST / HTTP/1.1" 200 -
HTTP POST to URL /some/endpoint received JSON {'a': 1}
127.0.0.1 - - [28/Aug/2017 11:57:51] "POST /some/endpoint HTTP/1.1" 200 -
HTTP GET to URL / received JSON {'a': 1}
127.0.0.1 - - [28/Aug/2017 11:57:55] "GET / HTTP/1.1" 200 -
一个简单的装饰者可以做到这一点:
from flask import Flask, request
app = Flask(__name__)
def print_if_post(*args, **kwargs):
def inner_decorator(f):
def inner(*args, **kwargs):
if request.method == 'POST':
json = request.get_json()
print("JSON Data: {}".format(json))
return f(*args, **kwargs)
return app.route(*args, **kwargs)(inner)
return inner_decorator
这个装饰器的功能与app.route完全相同,但会打印发送到其端点的任何JSON数据:
@print_if_post('/', methods=['POST', 'GET'])
def index():
return "True"
使用以下代码调用:
In [4]: requests.get('http://localhost:5000/')
Out[4]: <Response [200]>
In [5]: requests.post('http://localhost:5000/', json={'a': 1})
Out[5]: <Response [200]>
服务器输出:
In [2]: app.run(host='0.0.0.0')
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [28/Aug/2017 11:03:11] "GET / HTTP/1.1" 200 -
JSON Data: {'a': 1}
127.0.0.1 - - [28/Aug/2017 11:03:23] "POST / HTTP/1.1" 200 -