将服务器get到的响应打印,启动一个简单的web服务器,将post数据打印到cons

要打印出发送到服务器的任何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 -

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值