我想能够获得数据发送到我的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.get_data()。请求。data调用get_data(parse_form_data=True),而如果直接调用默认值为False。

其他回答

文档描述了请求期间请求对象(来自flask import request)上可用的属性。在大多数情况下请求。Data将为空,因为它被用作备用数据:

请求。data包含传入的请求数据作为字符串,以防它与mimetype Flask不处理。

request.args: the key/value pairs in the URL query string request.form: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encoded request.files: the files in the body, which Flask keeps separate from form. HTML forms must use enctype=multipart/form-data or files will not be uploaded. request.values: combined args and form, preferring args if keys overlap request.json: parsed JSON data. The request must have the application/json content type, or use request.get_json(force=True) to ignore the content type.

所有这些都是MultiDict实例(json除外)。您可以使用以下方法访问值:

请求。Form ['name']:如果知道键存在,则使用索引 Request.form.get ('name'):如果键可能不存在,则使用get Request.form.getlist ('name'):如果键被发送多次,并且你想要一个值列表,请使用getlist。Get只返回第一个值。

进口的要求:

from flask import request

URL查询参数:

name = request.args.get("name")
age = request.args.get("age")

表单输入:

name = request.form.get('name')
age = request.form.get('age')

OR(如果知道键存在,则使用索引,指定输入字段的名称)

name = request.form['name']
age = request.form['age']

JSON数据(适用于内容类型application/ JSON)

data = request.get_json()

试试- >

from flask import request

@app.route('/', methods=['GET', 'POST'])
def parse_request():
    if request.method == 'POST':
       data = request.form.get('data')

在编写一个Slack机器人时,它应该发送JSON数据,我得到了一个有效载荷,其中内容类型是application/x-www-form-urlencoded。

我尝试了request.get_json(),它没有工作。

@app.route('/process_data', methods=['POST'])
def process_data():
   req_data = request.get_json(force=True)

相反,我使用request。form获取包含JSON的表单数据字段,然后加载它。

from flask import json

@ app.route('/slack/request_handler', methods=['POST'])
def request_handler():
   req_data = json.loads(request.form["payload"])

您可以从

请求。表单数据,包括表单和文件数据, 请求。Json和请求。get_json用于JSON数据 请求。头对头 请求。参数来获取查询参数

它们都像字典,使用请求。Form ['name']如果你知道这个键存在,或者request.form.get('name')如果它是可选的。