要打印出发送到服务器的任何JSON,请构建一个基本的catch-all endpoint并从中打印JSON。在烧瓶中,如下所示:import logging
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'], defaults={'path': ''})
@app.route('/', methods=['POST', 'GET'])
def index(path):
print("HTTP {} to URL /{} received JSON {}".format(request.method, path, request.get_json()))
return "True"
以下是我打给服务器的电话:
^{pr2}$
以下是服务器输出: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
这个装饰器的功能与应用程序路径,但将打印发送到其端点的任何JSON数据:@print_if_post('/', methods=['POST', 'GET'])
def index():
return "True"
使用以下代码调用:In [4]: requests.get('http://localhost:5000/')
Out[4]:
In [5]: requests.post('http://localhost:5000/', json={'a': 1})
Out[5]:
服务器输出: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 -