0

I'm building a python endpoint on flask (which I'm pretty new to). I'm sending requests from PHP to it (as this is what the majority of our users will be using to send requests). I have a non-associative array of data that should be sent (i.e. something like 'mode' => array('foo', 'bar', 'baz'))

However in flask when doing str(request.form), all I am getting out is ImmutableMultiDict([('mode[1]', 'foo'), ('mode[0]', 'bar'), ('mode[2]', 'baz')])

Now from having looked around on stackoverflow (e.g. Sending array data with jquery and flask) I found this which suggested that I should be able to do something like request.form.getlist('mode[]') (with or without the square parenthesis - depending on which question you look at on here). However neither work.

Eventually I have found a temporary solution that if you json_encode the data before you put it into the curl post fields (i.e. you do 'mode' => json_encode(array('foo', 'bar', 'baz')) then things seem to be recieved nicely by Flask (ImmutableMultiDict([('mode', '["foo","bar","baz"]')]).

But I don't really understand why this solution works - I came across it by good luck rather than any sort of educated guess. Can anyone please explain the logic of why this works or if there is a better (TM) solution.

Thanks in advance!

Community
  • 1
  • 1
George Wilson
  • 5,595
  • 5
  • 29
  • 42

1 Answers1

0

You can do:

request.form.values()

This way you will get only the values from the dict's pairs as an array. You don't need to encode and decode the data to JSON just to read the values.

nstoitsev
  • 740
  • 8
  • 7
  • Sorry I should have made it clearer in my request. This isn't the entire post request. Mode is one of 3 array keys I am submitting! I just simplified things for the question – George Wilson Feb 15 '16 at 19:04
  • Yeah sorry it won't work if there are multiple keys. Have you tried this solution - http://stackoverflow.com/questions/24808660/sending-a-form-array-to-flask It's using [MultiDict.getlist](http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.MultiDict.getlist). – nstoitsev Feb 15 '16 at 19:07
  • Yeah that's the same answer to the SO post I linked to. But it fails because I have numeric index's in the mode variables in the ImmutableMultiDict object (or at least I'm assuming that's the issue) as all I get back is an empty list from getlist – George Wilson Feb 15 '16 at 19:11