Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending array data with jquery and flask

Tags:

jquery

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?

like image 697
tschm Avatar asked May 27 '14 12:05

tschm


2 Answers

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.

like image 131
Martijn Pieters Avatar answered Oct 17 '22 09:10

Martijn Pieters


You can use the flask function request.args.getlist('apps[]') to get the list from the js object you are passing to the server

var filter={}
 filter.startDate=$('#quant1').val(); 
 filter.endDate=$('#quant2').val(); 
 var checkedItems = [], counter = 0;
    $("#appNamesSelector div.active").each(function(idx, li) {
        checkedItems[counter] = $(li).text();
        counter++;
    });
filter.apps=checkedItems;
console.log($.param(filter));
    $.ajax({ type: "GET",   
 url: "/drilldown",
 data : filter  
});

Image shows how the array is passed into the server.

like image 23
joseph Avatar answered Oct 17 '22 09:10

joseph