user1998511 user1998511 - 6 months ago 46
Ajax Question

Handling a nested array in Flask request

I built a webserver in Flask and I'm passing in the request using jsonp. One of the things I pass in is an nested array and when I retrieve the data in Flask, the array is completely messed up.
Here's my code

index.html

var array = [[2,1],[2,2],[2,3]]
function getNext() {
var data = {
'M': 5,
'N': 5,
'array' : array
};
$.ajax({
url: '/getNewGeneration',
jsonp: 'callback',
dataType: 'jsonp',
data: data,
success: function(response) {
...
}
});
}


server.py

@app.route('/getNewGeneration')
def getNext():
M = request.args.get('M')
N = request.args.get('N')
liveCells = request.args.get('liveCells')
...


When I print out
request.args
I get
ImmutableMultiDict([('callback', u'jQuery17101683842277548142_1412736365518'), ('array[2][]', u'2'), ('array[2][]', u'3'), ('array[1][]', u'2'), ('array[1][]', u'2'), ('N', u'5'), ('M', u'5'), ('_', u'1412736417145'), ('array[0][]', u'2'), ('array[0][]', u'1')])


Does anyone know how to fix this?

Answer

I see two problems with your code. First, you don't pass a key named 'liveCells'. You pass one named 'array'. You need to update this either in your JavaScript or on the Flask side. Assuming you want the former, your JavaScript should look like

var array = [[2,1],[2,2],[2,3]]
function getNext() {
    var data = {
        'M': 5,
        'N': 5,
        'liveCells' : array
    };
    $.ajax({
        url: '/getNewGeneration',
        jsonp: 'callback',
        dataType: 'jsonp',
        data: data,
        success: function(response) {
            ...
        }
    });
}

Second, you can't use the get method to retrieve multivalve keys. ImmutableMultiDicts, such as request.args, provide a method called getlist that will return a list of items for the given key rather than a single value. Update your code to

liveCells = request.args.getlist('liveCells')

More information can be found in the werkzeug documentation.

Comments