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

2024-09-28 01:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中找到了一个simplewebserversnumber,它可以快速启动服务器并简单地响应请求。我需要的是一个服务器,它不仅打印每个请求(127.0.0.1 - - [28/Aug/2017 10:42:11] "POST / HTTP/1.1" 200 -)的IP地址、时间戳、方法和响应代码,而且,如果是POST请求,我需要它打印出POST数据。在

因此,例如,如果我发送一个POST请求,消息正文中有{"foo":"bar"},我希望服务器在响应之前将127.0.0.1 - - [28/Aug/2017 10:42:11] "POST / HTTP/1.1" 200 - {"foo":"bar"}打印到控制台。在

我不知道如何修改上面的链接选项。如果有另一个简单的选择,那也行得通。在


Tags: 数据方法代码服务器http消息numberfoo
1条回答
网友
1楼 · 发布于 2024-09-28 01:24:01

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

以下是我打给服务器的电话:

^{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]: <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 -

相关问题 更多 >

    热门问题