通过Cu向Flask发送JSON请求

2024-05-14 06:14:24 发布

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

我在烧瓶中设置了一个非常简单的后处理路径,如下所示:

from flask import Flask, request

app = Flask(__name__)

@app.route('/post', methods=['POST'])
def post_route():
    if request.method == 'POST':

        data = request.get_json()

        print('Data Received: "{data}"'.format(data=data))
        return "Request Processed.\n"

app.run()

这是我试图从命令行发送的curl请求:

curl localhost:5000/post -d '{"foo": "bar"}'

不过,它还是会打印出“接收到的数据:无”。所以,它无法识别我传递给它的JSON。

在这种情况下是否需要指定json格式?


Tags: fromimport路径jsonappflaskdata烧瓶
1条回答
网友
1楼 · 发布于 2024-05-14 06:14:24

根据^{}文件:

[..] function will return None if the mimetype is not application/json but this can be overridden by the force parameter.

因此,请指定传入请求的mimetype为application/json

curl localhost:5000/post -d '{"foo": "bar"}' -H 'Content-Type: application/json'

或者使用force=True强制JSON解码:

data = request.get_json(force=True)

如果在Windows上运行此命令(而不是PowerShell),则还需要将JSON数据的引号从单引号改为双引号:

curl localhost:5000/post -d "{\"foo\": \"bar\"}" -H 'Content-Type: application/json'

相关问题 更多 >