Python flask request returns undefined values - python

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}

Related

Pass array data through AJAX and get in python file(views.py)

I want to pass array data in views.py file for that I use AJAX and passing data through AJAX. But there I am not able to get all data in views.py file, some of the data are missing.
display.html
var SelectedID = [];
function getvalues() {
$(':checkbox:checked').each(function (i) {
SelectedID[i] = $(this).val();
console.log("Selected Data", SelectedID[i])
$.ajax({
url: "{% url 'addtoexisting' bid=adduser.id %}",
type: "POST",
dataType: "json",
data:{
SelectedID : SelectedID[i],
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (data) {
console.log("Selected Data AJAX", SelectedID)
alert("Successfully sent the Data to Django");
},
error: function (xhr, errmsg, err) {
// alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
}
});
});
}
views.py
def display(request):
is_ajax = request.headers.get('x-requested-with') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
SelectedID = request.POST.get('SelectedID')
print(SelectedID)
return render(request, 'display.html',{})
SelectedID[i] = $(this).val(); in this selectedID There are 10 records but in print of views.py there is only 6 records, other data are missing.

How to parse a jsonify object in python and display in html?

I have a flask app that returns the output from a jsonify function but the output that is displayed on the html is not pretty. I now to parse this output and modify it before returning it to the html. I tried to iterate over the json output but it doesn't let me do that. How do I do that?
First here is the output from the jsonify function on my webpage
Prediction: Apple Cedar rust,99.6459424495697,Bell_Pepper
healthy,0.2868120325729251,Blueberry healthy,0.05757397739216685
I want something like this
Predictions:
Apple Cedar rust: 99.6459424495697
Bell_Pepper healthy: 0.2868120325729251
Blueberry healthy: 0.05757397739216685
Now here is the code for the same in my app.py file
#app.route('/predict', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
# Get the file from post request
f = request.files['file']
# Save the file to ./uploads
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, 'uploads', secure_filename(f.filename))
f.save(file_path)
result = model_predict(file_path, model)
return jsonify(result)
return None
Finally here is the code for my main.js file
$.ajax({
type: 'POST',
url: '/predict',
data: form_data,
contentType: false,
cache: false,
processData: false,
async: true,
success: function (data) {
// Get and display the result
$('.loader').hide();
$('#result').fadeIn(600);
$('#result').text(' Prediction: ' + data);
console.log('Success!');
},
});
You can return an HTML string which can be utilized as the body of the #result div:
In your app.py, in upload:
...
result = model_predict(file_path, model)
return flask.jsonify({'html':'\n'.join(f'<p>{a}: {b}</p>' for a, b in result)})
In main.js:
$.ajax({
type: 'POST',
url: '/predict',
data: form_data,
contentType: false,
cache: false,
processData: false,
async: true,
success: function (data) {
// Get and display the result
$('.loader').hide();
$('#result').fadeIn(600);
$('#result').append(data.html); //add previously formatted html to div
console.log('Success!');
},
});
Javascript rendering of values:
In app.py:
import json
result = model_predict(file_path, model)
return flask.jsonify({'payload':json.dumps([{'name':a, 'val':b} for a, b in result])})
In main.js:
$.ajax({
type: 'POST',
url: '/predict',
data: form_data,
contentType: false,
cache: false,
processData: false,
async: true,
success: function (data) {
// Get and display the result
$('.loader').hide();
$('#result').fadeIn(600);
var new_data = JSON.parse(data.payload);
$('#result').append('Prediction: ');
for (var i in new_data){
var _html = `
<p>${new_data[i].name}: ${new_data[i].val}</p>
`
$('#result').append(_html);
}
console.log('Success!');
},
});
Assuming result is a valid json object passed into jasonify(result), you would need to iterate through the data object in your main.js and display the key:value pairs programmatically.
Something like this:
// data = { 'Apple Cedar rust': '99.6459424495697', ... }
$.each(data,function(key,value){
$('#results-list').append("<span>"+ key +": " + value + "</span>")
});

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)

Django API request is empty using React

So I am using axios in order to send a JSON request to Django API.
axios({
method: 'post',
url: 'http://127.0.0.1:8000/' + this.state.dataRequestEndPoint,
data: (reqData)
});
Just before the axios call I can see the request:
Object {nvm: "", a: Array(1), b: Array(1), c: Array(1), d: Array(1)}
However, when it gets to Django:
class TargetClass(APIView):
def get(self, request):
Here request is empty:
(Pdb) request.data
<QueryDict: {}>
(Pdb) request.body
b''
def post(self):
pass
What am I doing wrong?
P.S. Tried to send the request with fetch as well:
fetch('http://127.0.0.1:8000/' + this.state.dataRequestEndPoint, {
method: 'POST',
body: reqData,
})
None of it works.
Here is the solution for the problem above. Apparently, axios needs to send parameters:
var reqData = this.state.requestParams
axios({
method: 'post',
url: 'http://127.0.0.1:8000/' + this.state.dataRequestEndPoint,
params: {
'a': reqData['a'],
'b': reqData['b']
}
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
});
However, I don't know how good this solution is security-wise.

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);
}
});

Categories

Resources