Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

Sending array data with jquery and flask

I need to send data from a html page back into my Python application:

$.post("/test", {x: [1.0,2.0,3.0], y: [2.0, 3.0, 1.0]}, function(dat) {console.log(dat);});

on the server:

@app.route('/test', methods=['POST'])
def test():
    print request.form.keys()
    print dir(request.form)
    print request.form["x[]"]
    return jsonify({"Mean": 10.0})

Much to my surprise the keys are

['y[]', 'x[]']

and

print request.form["x[]"] 

results in 1.

What's the correct way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When sending POST data containing values that are arrays or objects, jQuery follows a PHP convention of adding brackets to the field names. It's not a web standard, but because PHP supports it out of the box it is popular.

As a result, the correct way of handling POST data with lists on the Flask side is indeed to append square brackets to the field names, as you discovered. You can retrieve all values of the list using MultiDict.getlist():

request.form.getlist("x[]")

(request.form is a MultiDict object). This returns strings, not numbers. If you know the values to be numbers, you can tell the getlist() method to convert them for you:

request.form.getlist("x[]", type=float)

If you don't want the additional brackets to be applied, don't use arrays as values, or encode your data to JSON instead. You'll have to use jQuery.ajax() instead though:

$.ajax({
    url: "/test",
    type: "POST",
    data: JSON.stringify({x: [1.0,2.0,3.0], y: [2.0, 3.0, 1.0]}),
    contentType: "application/json; charset=utf-8",
    success: function(dat) { console.log(dat); }
});

and on the server side, use request.get_json() to parse the posted data:

data = request.get_json()
x = data['x']

This also takes care of handling the datatype conversions; you posted floating point numbers as JSON, and Flask will decode those back to float values again on the Python side.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...