我想能够获得数据发送到我的Flask应用程序。我已经尝试访问请求。数据,但它是一个空字符串。如何访问请求数据?

from flask import request

@app.route('/', methods=['GET', 'POST'])
def parse_request():
    data = request.data  # data is empty
    # need posted data here

这个问题的答案让我问在Python Flask中获取原始POST体,而不管接下来的Content-Type头,这是关于获取原始数据而不是解析数据。


当前回答

如果主体被识别为表单数据,则它将在request.form中。如果它是JSON,它将在request.get_json()中。否则原始数据将在request.data中。如果您不确定数据将如何提交,您可以使用or链来获得第一个有数据的链。

def get_request_data():
    return (
        request.args
        or request.form
        or request.get_json(force=True, silent=True)
        or request.data
    )

请求。Args包含从查询字符串中解析出来的参数,而不管主体中有什么,所以如果它和主体同时需要数据,那么您将从get_request_data()中删除它。

其他回答

得到请求。form作为普通字典,使用request.form.to_dict(flat=False)。

要为API返回JSON数据,请将其传递给jsonify。

这个示例将表单数据作为JSON数据返回。

@app.route('/form_to_json', methods=['POST'])
def form_to_json():
    data = request.form.to_dict(flat=False)
    return jsonify(data)

下面是一个使用curl的POST表单数据的例子,返回为JSON:

$ curl http://127.0.0.1:5000/data -d "name=ivanleoncz&role=Software Developer"
{
  "name": "ivanleoncz", 
  "role": "Software Developer"
}

在JavaScript中使用jQuery发布JSON,请使用JSON。Stringify来转储数据,并将内容类型设置为application/json。

var value_data = [1, 2, 3, 4];

$.ajax({
    type: 'POST',
    url: '/process',
    data: JSON.stringify(value_data),
    contentType: 'application/json',
    success: function (response_data) {
        alert("success");
    }   
});

在Flask中使用request.get_json()解析它。

data = request.get_json()

在使用HTML表单发布表单数据时,请确保输入标记具有name属性,否则它们将不会出现在request.form中。

@app.route('/', methods=['GET', 'POST'])
def index():
    print(request.form)
    return """
<form method="post">
    <input type="text">
    <input type="text" id="txt2">
    <input type="text" name="txt3" id="txt3">  
    <input type="submit">
</form>
"""
ImmutableMultiDict([('txt3', 'text 3')])

只有txt3输入有名称,所以它是request.form中唯一的键。

如果你用内容类型application/ JSON发布JSON,使用request.get_json()在Flask中获取它。如果内容类型不正确,则返回None。如果数据不是JSON,则会引发错误。

@app.route("/something", methods=["POST"])
def do_something():
    data = request.get_json()
request.data

这很好用,但请记住,它是作为字符串传入的,需要遍历。