MattM
MattM

Reputation: 1289

Python Bottle: Accessing array variable inside request POST data

I was recently handed a partially-completed project and I'm new to using Bottle. I have a situation where I'm sending a dictionary inside an AJAX request and Bottle is on the server side. The dictionary looks something like this (in JavaScript):

var myInt = 5;
var myArray = [0, 1, 2];
var data = {
    myInt: myInt,
    myArray: myArray
};

Then, in Python, I want to read in this data. I can't seem to get the array. I can get the int just fine. I've tried several things, but here's what made most sense to me that still didn't work:

try:
    myInt = int(request.forms.get('myInt'))
    myArray = request.forms.getall('myArray')

This results in an empty list for myArray. Can anyone point me in the right direction? I've read every similar question on StackOverflow to no avail.

I know I could turn this into a string separated by pipes or something, but I would like to see if arrays are possible to send like this.

Thanks!

Upvotes: 0

Views: 3817

Answers (3)

Camilo Barbosa
Camilo Barbosa

Reputation: 21

var myInt = 5;
var myArray = [0, 1, 2];
var data = {
    myInt: myInt,
    myArray: JSON.stringify(myArray)
};

Use JSON.stringify in js and in bottle json_loads():

myInt = request.params.get('myInt')
myArray =  json_loads(request.params.get('myArray'))

Upvotes: 0

ron rothman
ron rothman

Reputation: 18128

Not sure whether this is the only problem, but (I think) you may be confusing JSON arrays and the use of getall. You should use get, not getall, here:

myArray = request.params.get('myArray')

If I understand the code correctly, getall is for the case when you have multiple args with the same name, as in http://example.com/get?foo=1&foo=2.

On the other hand, your myArray variable is just a single reference to an array.

Hope this helps (even if it doesn't solve your problem).

Upvotes: 1

ron rothman
ron rothman

Reputation: 18128

Use request.json:

try:
    myInt = request.json['myInt']
    myArray = request.json['myArray']

(Assumes your client is setting content-type to application/json.)

Here's a nice example.

Upvotes: 1

Related Questions