How to get data received in Flask request

2018-12-31 00:17发布

I want to be able to get the data sent to my Flask app. I've tried accessing request.data but it is an empty string. How do you access request data?

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

The answer to this question led me to ask Get raw POST body in Python Flask regardless of Content-Type header next, which is about getting the raw data rather than the parsed data.

标签: python flask
15条回答
爱死公子算了
2楼-- · 2018-12-31 00:37

if you want the raw post body regardless of the content type, you should use request.get_data(), because request.form is converted to werkzeug.ImmutableMultiDict format.

查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 00:42

It is simply as follows

For URL Query parameter, use request.args

search = request.args.get("search")
page = request.args.get("page")

For Form input, use request.form

email = request.form.get('email')
password = request.form.get('password')

For data type application/json, use request.data

# data in string format and you have to parse into dictionary
data = request.data
dataDict = json.loads(data)
查看更多
还给你的自由
4楼-- · 2018-12-31 00:43

I give a full example of application/json:

from flask import Flask, abort, request 
import json

app = Flask(__name__)


@app.route('/foo', methods=['POST']) 
def foo():
    if not request.json:
        abort(400)
    print request.json
    return json.dumps(request.json)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

use Postman for post request:

enter image description here

use curl command:

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

P.S. For URL Query parameter example, you can see my answer in Multiple parameters in in Flask approute

查看更多
高级女魔头
5楼-- · 2018-12-31 00:44
len = request.headers["Content-Length"]
data=request.stream.read()

Now, data is the request body

查看更多
长期被迫恋爱
6楼-- · 2018-12-31 00:45

Flask has another shortcut for JSON:

Header:

{Content-Type: application/json}

@app.route("/something", methods=["POST"])
def do_something():
    data = request.get_json()
查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 00:45

Using request.form.

Instead of getting a single form data (request.form["field_name"]), you can obtain all posted data, by parsing the ImmutableDict provided by request.form object, like this:

Flask (Route)

@app.route('/data', methods=['POST'])                                           
def f_data():                                                                   
    if request.method == "POST":
        fields = [k for k in request.form]                                      
        values = [request.form[k] for k in request.form]
        data = dict(zip(fields, values))
    return jsonify(data) 

Shell

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

For more details, this Gist.

查看更多
登录 后发表回答