我想能够获得数据发送到我的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头,这是关于获取原始数据而不是解析数据。


当前回答

要获得没有application/ JSON内容类型的JSON,请使用request.get_json(force=True)。

@app.route('/process_data', methods=['POST'])
def process_data():
    req_data = request.get_json(force=True)
    language = req_data['language']
    return 'The language value is: {}'.format(language)

其他回答

试试- >

from flask import request

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

原始数据作为request.stream从WSGI服务器传递到Flask应用程序。流的长度在Content-Length报头中。

length = request.headers["Content-Length"]
data = request.stream.read(length)

通常使用request.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,使用request.get_json()。

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

下面是一个解析发布的JSON数据并将其回显的示例。

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/foo', methods=['POST']) 
def foo():
    data = request.json
    return jsonify(data)

使用curl发布JSON:

curl -i -H "Content-Type: application/json" -X POST -d '{"userId":"1", "username": "fizz bizz"}' http://localhost:5000/foo

或者使用Postman: