For my single page web app, I need to:
Send a json from .js to flask (DONE)
Run the input through a python function - getString() and get a str output (DONE)
Send the str output back to the .js file (PROBLEM)
Here is the flask app:
#app.route('/',methods =['GET','POST'])
def index():
req = json.dumps(request.get_json())
if request.method == 'POST':
result = getString(req) #Function outputs a string
return jsonify(result)
else:
print('Not Received')
return render_template('index.html')
if __name__ == '__main__':
app.run()
The problem is that the jsonify(result) is not being sent probably due to the request.method == 'POST' switching to else when jsonify is called. Is there any way to fix my code to send the str output to the .js?
Here is the .js:
//To send info to flask
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json"
});
})
//To receive from Flask
$.ajax({
url: "/",
type: 'GET',
success: function(data) {
console.log(data);
}
});
I think you've misunderstood what GET and POST are, GET is a request that only fetches something from the back end without a message body but a POST can send a body and recieve something.
try this instead:
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json",
success: function(data) {
console.log(data);
}
});
})
Related
i have issue to send data in flask from js. I try use ajax.
AJAX code
$.ajax({
type: "GET",
contentType: "application/json;charset=utf-8",
url: "/getmethod/data",
traditional: "true",
data: JSON.stringify({data}),
dataType: "json"
});
Python code
def get_javascript_data(data):
content = request.get_data('data')
jsonify(content)
If u got some tips or tricks please tell me.
new_item = $('#input').val() //value I want to send
$.ajax({
url: '/set_value',
type: 'POST',
data: new_item,
success: function(response){
$('#main').text(response)
}
})
in flask:
new_item = request.get_data()
I'm training a CNN model by KERAS. I want to show the model's predict results in Flask web page.The trouble is that I want to return a dictionary data from my local python program and show the data in Flask web page, but I can't parse the JSON correctly and show the items by line. Because I have little knowledge in JS :(
I want the web page shows like this
笔迹最相似的5个书写人:
top5_index[0] top5_prob[0]
top5_index[1] top5_prob[1]
top5_index[2] top5_prob[2]
top5_index[3]:top5_prob[3]
top5_index[4] top5_prob[4]
however the web page shows nothing...(I guess the JS part code went wrong)
There is my codes, and the it doesn't work.
python
#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)
# Make prediction
top5_index, top5_prob = model_predict(file_path, model)
wr_dict = {top5_index[0]:top5_prob[0], top5_index[1]:top5_prob[1],
top5_index[2]:top5_prob[2], top5_index[3]:top5_prob[3],
top5_index[4]:top5_prob[4]}
return json.dumps(wr_dict)
return None
JS
// Predict
$('#btn-predict').click(function () {
var form_data = new FormData($('#upload-file')[0]);
$(this).hide();
$('.loader').show();
// Make prediction by calling api /predict/
$.ajax({
type: 'POST',
url: '/predict',
data: JSON.parse(form_data),
contentType: 'application/json;charset=utf-8',
dataType: 'json',
cache: false,
processData: false,
async: true,
success: function (data) {
// Get and display the result
$('.loader').hide();
$('#result').fadeIn(600);
$('#result').text(' 笔迹最相似的5个书写人: ');
$('#value1').text(data[0]);
$('#value2').text(data[1]);
$('#value3').text(data[2]);
$('#value4').text(data[3]);
$('#value5').text(data[4]);
console.log('Success!');
},
});
});
How to change the JS part code to display the dictionary data in the correct format.
Any help will be appreciated.
You should use flask.jsonify for responses:
import flask
return flask.jsonify(**wr_dict)
It does a bit more than dumps, according to the docs:
This function wraps dumps() to add a few enhancements that make life easier. It turns the JSON output into a Response object with the application/json mimetype.
And on your JS end, you should stringify the data and not parse it (dict -> string), then parse the response (string -> dict):
// Make prediction by calling api /predict/
$.ajax({
type: 'POST',
url: '/predict',
data: JSON.stringify(form_data), // CHANGED HERE
contentType: 'application/json;charset=utf-8',
dataType: 'json',
cache: false,
processData: false,
async: true,
success: function(data) {
data = JSON.parse(data); // CHANGED HERE
// Get and display the result
$('.loader').hide();
$('#result').fadeIn(600);
$('#result').text(' 笔迹最相似的5个书写人: ');
$('#value1').text(data[0]);
$('#value2').text(data[1]);
$('#value3').text(data[2]);
$('#value4').text(data[3]);
$('#value5').text(data[4]);
console.log('Success!');
},
});
Thank you #AdamGold :)
I tried your codes, however the web page didn't show the data. I checked the browser's console but it didn't report error, and codes in success: function(data) {} was not executed.
I guess it also fails to parse the data(return by flask.jsonify). Today I find a method to parse the JSONstring data correctly and display it in the web page. Still I use the json.dumps in my python file, and the dictionary is slightly modified. And in my file I change the code like this:
...
# Make prediction
top5_index, top5_prob = model_predict(file_path, model)
wr_dict = {"index1":top5_index[0], "prob1":top5_prob[0],
"index2":top5_index[1], "prob2":top5_prob[1],
"index3":top5_index[2], "prob3":top5_prob[2],
"index4":top5_index[3], "prob4":top5_prob[3],
"index5":top5_index[4], "prob5":top5_prob[4]}
return json.dumps(wr_dict)
return None
// Predict
$('#btn-predict').click(function () {
var form_data = new FormData($('#upload-file')[0]);
// Show loading animation
$(this).hide();
$('.loader').show();
// Make prediction by calling api /predict
$.ajax({
type: 'POST',
url: '/predict',
data: form_data,
contentType: false,
cache: false,
processData: false,
async: true,
success: function (data) {
var data_obj = $.parseJSON(data);
$('.loader').hide();
$('#result').fadeIn(600);
$('#result').text('笔迹最相似的5个书写人:');
$('#value1').text('编号及概率:'+data_obj["index1"]+'------'+data_obj["prob1"]);
$('#value2').text('编号及概率:'+data_obj["index2"]+'------'+data_obj["prob2"]);
$('#value3').text('编号及概率:'+data_obj["index3"]+'------'+data_obj["prob3"]);
$('#value4').text('编号及概率:'+data_obj["index4"]+'------'+data_obj["prob4"]);
$('#value5').text('编号及概率:'+data_obj["index5"]+'------'+data_obj["prob5"]);
console.log('Success!');
},
});
});
Thank you. I will learn more JS knowledge.
I want to sent data in json format from a webpage to flask using ajax post method. My tries are as follows :
MY TRY: mytest.html(code snippet)
var jsondat = JSON.stringify(table.getData());
console.log(jsondat);
$.ajax({
type: 'POST',
url: '127.0.0.1:5000/test',
// contentType: 'application/json;charset=UTF-8',
data: {
'data': jsondat
},
success: function(response) {
alert("HELLO")
},
});
Flask App:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/<string:page_name>/')
def render_static(page_name):
return render_template('%s.html' % mytest)
#app.route('/test')
def testfun():
content = request.get_json(silent=True)
print(content)
return 'The test'
if __name__ == '__main__':
app.run()
I am using ajax to POST a JSON string to Python Flask but get the following error:
Error
This is my JavaScript:
$.ajax({
type: 'POST',
url: window.location.href,
data: JSON.stringify(questionObj0),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
console.log(msg);
});
And this is my Python:
#app.route('/test', methods=['GET', 'POST'])
def test():
question = request.get_json()
question1 = json.loads(question)
print (question)
return render_template('test.html')
Using print(question) yields the following output (same output when tested in JavaScript using browsers console):
{'questionNumber': 1, 'question': 'Convert 10110001 to decimal', 'answer': 177, 'userAnswer': 'blank'}
From what I understand, the output should be a string and therefore padded with quotation marks.
Has anyone come across anything similar/know how to fix the issue?
Flask's request.get_json() returns a dict object from the JSON data supplied in the request, so you don't need to call json.loads on it again.
app.py
#app.route('/', methods=['GET'])
def index():
return render_template('index.html')
#app.route('/test', methods=['POST'])
def test():
question = request.get_json()
print(question['question'])
return ''
templates/index.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var questionObj0 = {'questionNumber': 1, 'question': 'Convert 10110001 to decimal', 'answer': 177, 'userAnswer': 'blank'};
console.log(JSON.stringify(questionObj0));
$.ajax({
type: 'POST',
url: '{{ url_for('test') }}',
data: JSON.stringify(questionObj0),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
console.log(msg);
});
</script>
I'm a complete beginner here and facing a problem in passing javascript variable into flask. Please note that my question is completely different from previous question that has been asked.
This is my code:
JavaScript
var dd = {'mvar': 1};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/",
data: JSON.stringify(dd),
success: function (data) {
alert("DONE!")
},
dataType: "json"
});
Flask(edited)
#app.route('/', methods=['GET', 'POST'])
def new():
form = InputForm(request.form)
v = request.get_json().get('mvar')
print(v)
return render_template('new.html',form=form,v=v)
However, when the output that I get when print out the result is "None" while I expected it to be "1"
Really hope that experts can help me, thank you!
The Request.get_json() method is what you are looking for in your Flask code.
data = request.get_json()
edit here is the exact pattern i use which works:
javascript:
$.ajax({
type: "POST",
url: "{{ url_for("get_post_json") }}",
contentType: "application/json",
data: JSON.stringify({hello: "world"}),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(err) {
console.log(err);
}
});
python:
#app.route('/_get_post_json/', methods=['POST'])
def get_post_json():
data = request.get_json()
return jsonify(status="success", data=data)
Instead of using
v = request.form.get('mvar', type=int)
Use this
v = request.get_json().get('mvar')
Once you print v then you should get it.