1

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?

2
  • is request.json also that messed up? Commented Oct 8, 2014 at 3:30
  • request.json returned None Commented Oct 8, 2014 at 23:45

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the only answer I've found on SO that mentions there is a getList function, so thank you for pointing that out.
0

Do it like this and i think it will work for you.

$.ajax({
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(data),
    dataType: 'json',
    url: 'getNewGeneration',
    success: function (e) {
        console.log(e);
    }
});

And try to print request.json then.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.