how to get data from 'ImmutableMultiDict' in flask
Question:
I am learning how to use ajax and Flask ,so what I do is I send a ajax request and I receive the data as post
request in my python file
My html file contains this code
var data = {"name":"John Doe","age":"21"};
$.ajax({
url:'/post/data',
datatype : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
jQuery("#clash").html(result);
},error : function(result){
console.log(result);
}
});
And My python file contains :
@app.route('/post/data',methods=['GET','POST'])
def postdata():
#do some
data = str(request.args)
json_dumps = json.dumps(data)
return json_dumps
This gives me following data on the page
"ImmutableMultiDict([('{"name":"John Doe","age":"21"}', u'')])"
And this is what my request.query_string
looks {%22name%22:%22John%20Doe%22,%22age%22:%2221%22}
So how do I get the name
and age
. Please correct me If I am wrong anywhere.Thanks in advance.
Answers:
You don’t actually need to get data from an ImmutableMultiDict
. There are a couple of errors in what you have that are preventing you from just pulling the response as json data. First off, you have to slightly tweak the parameters of your ajax call. You should add in the call type as a POST
. Furthermore, datatype
should be spelt as dataType
. Your new call should be:
var data = {"name":"John Doe","age":"21"};
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/post/data',
dataType : 'json',
data : JSON.stringify(data),
success : function(result) {
jQuery("#clash").html(result);
},error : function(result){
console.log(result);
}
});
The data is now actually being sent as a post request with the json
type. On the Flask server, we can now read the data as son information as follows:
@app.route('/post/data',methods=['GET','POST'])
def postdata():
jsonData = request.get_json()
print jsonData['name']
print jsonData['age']
return "hello world" #or whatever you want to return
This will print John Doe
and 21
successfully.
Let me know if this works for you or if you have any additional questions!
Edit: You can return success to the ajax call from flask as follows:
# include this import at the tomb
from flask import jsonify
@app.route('/post/data',methods=['GET','POST'])
def postdata():
...
return jsonify(success=True, data=jsonData)
I came to this page because I’m trying to send a form with AJAX, and I finally found a solution. And the solution is to skip JSON (hope this will help others on the same search):
$.ajax({
type: "POST",
url: my_url,
data: $("#formID").serialize(), //form containing name and age
success: function(result){
console.log(result);
}
});
Then, on the Flask server:
app.route('/my_url', methods = [POST])
def some_function():
name = request.form['name']
age = request.form['age']
# do what you want with these variables
return 'You got it right'
Just call to_dict on the request.form object E.g., http://www.seanbehan.com/how-to-get-a-dict-from-flask-request-form/
I solved the problem by adding the contentType as application/JSON like so
data ={
type:'POST',
contentType:'application/json',
otherData: 'foo'
}
You can now access the data in the flask backend like so:
app.route('/my_url', methods = ["POST"])
def some_function():
other_data = request.form['otherData']
# do something
Note: I used vanilla JavaScript for this not jQuery
This work for me:
var data = {"name":"John Doe","age":"21"};
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/my_url',
dataType : 'json',
data : JSON.stringify(data),
success : function(result) {
jQuery("#clash").html(result);
},error : function(result){
console.log(result);
}
});
In flask App:
improt json
@app.route('/my_url',methods=['POST,GET']) #
def some_function():
dataList=list(request.form)[0] # output is string ==> '{"name":"John Doe","age":"21"}'
b=json.loads(dataList) # output is dictionary ==> {"name":"John Doe","age":"21"}
print(b) #{"name":"John Doe","age":"21"}
return 'OK'
I am learning how to use ajax and Flask ,so what I do is I send a ajax request and I receive the data as post
request in my python file
My html file contains this code
var data = {"name":"John Doe","age":"21"};
$.ajax({
url:'/post/data',
datatype : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
jQuery("#clash").html(result);
},error : function(result){
console.log(result);
}
});
And My python file contains :
@app.route('/post/data',methods=['GET','POST'])
def postdata():
#do some
data = str(request.args)
json_dumps = json.dumps(data)
return json_dumps
This gives me following data on the page
"ImmutableMultiDict([('{"name":"John Doe","age":"21"}', u'')])"
And this is what my request.query_string
looks {%22name%22:%22John%20Doe%22,%22age%22:%2221%22}
So how do I get the name
and age
. Please correct me If I am wrong anywhere.Thanks in advance.
You don’t actually need to get data from an ImmutableMultiDict
. There are a couple of errors in what you have that are preventing you from just pulling the response as json data. First off, you have to slightly tweak the parameters of your ajax call. You should add in the call type as a POST
. Furthermore, datatype
should be spelt as dataType
. Your new call should be:
var data = {"name":"John Doe","age":"21"};
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/post/data',
dataType : 'json',
data : JSON.stringify(data),
success : function(result) {
jQuery("#clash").html(result);
},error : function(result){
console.log(result);
}
});
The data is now actually being sent as a post request with the json
type. On the Flask server, we can now read the data as son information as follows:
@app.route('/post/data',methods=['GET','POST'])
def postdata():
jsonData = request.get_json()
print jsonData['name']
print jsonData['age']
return "hello world" #or whatever you want to return
This will print John Doe
and 21
successfully.
Let me know if this works for you or if you have any additional questions!
Edit: You can return success to the ajax call from flask as follows:
# include this import at the tomb
from flask import jsonify
@app.route('/post/data',methods=['GET','POST'])
def postdata():
...
return jsonify(success=True, data=jsonData)
I came to this page because I’m trying to send a form with AJAX, and I finally found a solution. And the solution is to skip JSON (hope this will help others on the same search):
$.ajax({
type: "POST",
url: my_url,
data: $("#formID").serialize(), //form containing name and age
success: function(result){
console.log(result);
}
});
Then, on the Flask server:
app.route('/my_url', methods = [POST])
def some_function():
name = request.form['name']
age = request.form['age']
# do what you want with these variables
return 'You got it right'
Just call to_dict on the request.form object E.g., http://www.seanbehan.com/how-to-get-a-dict-from-flask-request-form/
I solved the problem by adding the contentType as application/JSON like so
data ={
type:'POST',
contentType:'application/json',
otherData: 'foo'
}
You can now access the data in the flask backend like so:
app.route('/my_url', methods = ["POST"])
def some_function():
other_data = request.form['otherData']
# do something
Note: I used vanilla JavaScript for this not jQuery
This work for me:
var data = {"name":"John Doe","age":"21"};
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/my_url',
dataType : 'json',
data : JSON.stringify(data),
success : function(result) {
jQuery("#clash").html(result);
},error : function(result){
console.log(result);
}
});
In flask App:
improt json
@app.route('/my_url',methods=['POST,GET']) #
def some_function():
dataList=list(request.form)[0] # output is string ==> '{"name":"John Doe","age":"21"}'
b=json.loads(dataList) # output is dictionary ==> {"name":"John Doe","age":"21"}
print(b) #{"name":"John Doe","age":"21"}
return 'OK'