Handling a nested array in Flask request - python

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?

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.

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.

Related

Python flask request returns undefined values

I want to pass array to Python Flask but I got empty result or b'undefined=&undefined=&undefined='. Here is my code
Javascript
var test = [1, 2, 3];
$.ajax({
url: '/table',
data : test,
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
and Python code
app.route('/table', methods = ['POST'])
def table():
#print(request.values)
print(request.get_data())
return 'got this'
You need to use JSON to send back values that are arrays, objects, etc in javascript:
var test = [1, 2, 3];
$.ajax({
url: '/table',
data : {'payload':JSON.stringify(test)},
type: 'get',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
Then, in the app:
import json
#app.route('/table')
def table():
_result = json.loads(flask.request.args.get('payload'))
return 'got this'
Use JavaScript object and send as content as application/json.
var test = {'input_1': 1, 'input_2': 2, 'input_3': 3};
$.ajax({
url: '/table',
data : JSON.stringify(test),
contentType: 'application/json',
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
In your flask app, you don't need import json to load received data because you have sent content as application/json.
from flask import jsonify, request
#app.route('/table', methods = ['POST'])
def table():
_result = request.json # because you have sent data as content type as application/json
return jsonify(_result) # jsonify will response data as `application/json` header.
# {'input_1': 1, 'input_2': 2, 'input_3': 3}

Passing Dict of Arrays using Ajax and Django

I have a dictionary of arrays that I would like to pass to my Django view.
$.ajax({
url: '/fund_monitor/fund_directory',
type: 'GET',
data:{
filter_dict: filter_dict,
},
success: function (data) {
console.log(filter_dict);
}
});
And in my view I would like to receive this dict:
if request.is_ajax():
filter_dict = request.GET.getlist('filter_dict')
print("Is Ajax", filter_dict)
But "Is Ajax []" gets printed out and just as an example, my filter_dict:
Designated Broker:["BMO"]
Fund Class:["OM"]
Any ideas why a blank array gets passed?
$.ajax({
url: '/fund_monitor/fund_directory',
type: 'GET',
data:JSON.stringify({
filter_dict: filter_dict,
}),
success: function (data) {
console.log(filter_dict);
}
});
if request.is_ajax():
request_data = json.loads(request.GET)
filter_dict = request_data['filter_dict']
print("Is Ajax", filter_dict)

Unclear 404 get ajax error passing integer to django

Totally unclear 404 Ajax error.
var int_page_number = 2;
$.ajax({
type:'GET',
url: '/loadmore/',
data: { 'page_number' : int_page_number},
dataType: 'json',
success: function (data) {
alert(data);
}
});
In the place passing data, I tried both using apostrophe and not around page_number. It's 404 so error may be in frontedn, but anyways I attach django urls.py string just in case :
url(r'^loadmore/(?P<page_number>[0-9]+)/$', views.loadmore),
and views.py function, which is all right:
#api_view(['GET', ])
def loadmore(request,page_number):
answers_to_questions_objects = Question.objects.filter(whom=request.user.profile).filter(answered=True).order_by('-answered_date')
paginator = Paginator(answers_to_questions_objects,10)
current_page = (paginator.page_number)
answers = serializers.serialize('json', current_page)
data = {
'answers': answers
}
return Response(data)`
For your url you should make a call to the url like /loadmore/2/, but you make the call like /loadmore/?page_number=2. So your ajax should be like this:
var int_page_number = 2;
$.ajax({
type:'GET',
url: '/loadmore/' + int_page_number + '/',
success: function (data) {
alert(data);
}
});

Unable to pass html button to Flask [duplicate]

function CallMethod() {
$.getJSON('/website/RESTfulService.svc/LiveLocation/json?{x=1,y=2}', function(data) {
getResult(data.lat, data.lon);
});
}
Pass them as an object just after the URL and before the function:
function CallMethod() {
$.getJSON('/website/RESTfulService.svc/LiveLocation/json',
{
x: "1",
y: "2"
},
function(data) {
getResult(data.lat, data.lon);
});
}
Alternatively, first create javascript object for the sake of simplicity and then pass
var myObject = {x: "1", y: "2"};
$.getJSON('/website/RESTfulService.svc/LiveLocation/json', myObject, function(dataVal) {
//Use Your result
});
Just like Zheileman said, but note that this way, although you passed the parameters in JSON format, the actual parameters are passed to the webserver as an Encoded HTTP URL which will end up this way:
/website/RESTfulService.svc/LiveLocation/json?x=1&y=2

Accessing nested objects in django POST request using python 3

I am having some trouble accessing nested objects from an ajax post call. Here is my js:
$.ajax({
url: "/api/locate/",
type: "POST",
data: {start:
{
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
},
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
console.log(start);
},
success: function(data) {
console.log(data);
}
})
in my views, the only way I can retrieve the data is by doing the following:
latitude = request.POST['start[latitude]']
longitude = request.POST['start[longitude]']
which is kinda bad considering that optimally I'd like to have start as the dictionary containing the latitude and longitude keys. I do realize this formatting is due to the content type being set to "application/x-www-form-urlencoded", but when I change it to "application/json", the data must be decoded from request.body:
decoded = request.body.decode('utf8')
data = json.loads(decoded)
which in turn raises the following ValueError:
Expecting value: line 1 column 1 (char 0)
The decoded string is:
start%5B0%5D%5Blatitude%5D=31.736784000000004&start%5B0%5D%5Blongitude%5D=-106.473027
Has any of you had any luck on properly loading nested objects or am I stuck with the first method?
EDIT: Using Django 1.6.2 and python 3.4
When you send json data, use the JSON stringifier on your object.
data: JSON.stringify({start:
{
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
})
If you pass a plain Object as data, it is converted to a query string, no matter what you declare as Content-Type.

Categories

Resources