This question already has an answer here:
Flask view raises TypeError: 'bool' object is not callable
(1 answer)
Closed 6 years ago.
I am extremely new to javascript/ajax/flask and am trying to get data from my flask server. I am rendering the client.html template and need to get data from the /data route.
app = Flask(__name__)
#app.route("/data", methods=["GET"])
def submit_handler():
return 10 #example value
#app.route('/client')
def page():
return render_template('client.html')
if __name__ == '__main__':
app.run()
In client.html:
var output = $.ajax({
url: "/data",
type: "GET",
})
window.alert(output)
The window alert outputs:
[object Object]
Why doesn't this output 10? Sorry if this question is too basic, but similar searches haven't helped me in understanding data requests.
Try this simply
$.get( "/data", function(data, success){
window.alert(data)
})
EDIT:
#app.route("/data", methods=["GET"])
def submit_handler():
return "10" #str(10)
cause
In Flask, a view must return one of the following:
a string
a Response object (or subclass)
a tuple of (string, status,headers) or (string, status)
a valid WSGI application
For more Flask view raises TypeError: 'bool' object is not callable
Try this,
$.ajax({
url: "/data",
type: "GET",
datatype : "text",
success: function(output){
console.log(output);
}
})
Or alternatively check for the type of object being returned by checking the response in developer tools. Use F12 to open developer tools in your browser where you can see the response being returned.
Related
I have a flask restful server. I am able to post from Python shell using request.post when I go like this in the post method (on the server):
def post:
get_data = request.get_json()
obj_data = json.loads(get_data)
But the same thing fails, if I try to post using Ajax from js:
json_data = JSON.stringify(data)
$.ajax({
type: "POST",
contentType: "application/json",
url:'mysite',
data:json_data,
dataType: "json"
})
And, the error is TypeError: expected string or buffer
If I remove the json.loads from the server like below, the JS code runs but Python fails with error AttributeError: 'unicode' object has no attribute 'iteritems'
def post:
get_data = request.get_json()
What changes should I make to make the server accept request from both JS and Python ?
This question already has answers here:
How do I write JSON data to a file?
(16 answers)
Closed 5 years ago.
Trying to understand how to send post requests to my backend (flask).
In my HTML I have 3 checkboxes and a submit button. My submit button returns a javascript array and I'm trying to send that javascript array to an api endpoint 'api/regions' which you can see below.
$(document).ready(function() {
$("#loadData").click(getChecked);
});
function getChecked() {
event.preventDefault();
var checkboxes = $(".form-check input[type=checkbox]:checked");
//toArray: convert checkboxes object to javascript array
var labels = checkboxes.toArray().map(checkbox => checkbox.value);
$.ajax({
url: 'api/regions',
type: "POST",
data: JSON.stringify(labels),
processData: false,
contentType: "application/json; charset=UTF-8",
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
In my app.py I have a route for my endpoint api:
#app.route('/api/regions', methods=['POST'])
def regions():
regions = request.json
with open("C:\\test.txt", 'w') as f:
f.write(regions)
if __name__ == "__main__":
app.run(debug=True)
I understand there is no return statement, I'm just trying to write the data I get from
regions = request.json
to a file. "C:\test.txt"
The error I'm getting when trying to do this is 500 which doesn't give me a lot to work with. I'm not sure if what I'm missing is on the front end or back end so hopefully someone could shed some light on where I'm going wrong.
From the flask documentation,
If the mimetype is application/json this will contain the parsed JSON data. Otherwise this will be None.
The key there is that .json is the parsed JSON data, not the original string. If you want to write it to a file, you'll need to convert it back to a string it first, perhaps by using json.dumps():
with open("C:\\test.txt", 'w') as f:
f.write(json.dumps(regions))
I am experimenting with Flask and AJAX, I have a simple API route here , hosted at OpenShift. I want to call the API in a Javascript file with Ajax. The OpenShift Python file is simple:
from flask import Flask
app = Flask(__name__)
import json
#app.route('/hello/<name>')
def hello_world(name=None):
str = {'key':'Hello World!', 'q':name}
#out = {'key':str}
res = json.dumps(str)
return res
if __name__ == '__main__':
app.run()
And here is the Ajax call:
$.ajax({
type:"GET",
dataType: "json",
data:'Payam',
url: "http://mypythonapp-spacepirate.rhcloud.com/hello/",
success: function(data){
buf1=data;
console.log(data);
}
})
But this makes a call to this url which results in 404. How can I solve this? Just to mention CORS is not an issue.
http://mypythonapp-spacepirate.rhcloud.com/hello/?Payam
Try changing your url property to
url: "http://mypythonapp-spacepirate.rhcloud.com/hello/world",
Then you will get a 200 response status, instead of the 404. The reason is the flask route you created has a required parameter after the hello/.
edit: followup to question about using variable for the data
method1: just add encode the parameter to the url
url: "http://mypythonapp-spacepirate.rhcloud.com/hello/" + encodeURIComponent(xyz)
method2: use the data parameter to the ajax call as you have started to do. I think that jquery will translate that into the URL query string for a get, like this. Notice the ? delimiting the start of query string:
http://mypythonapp-spacepirate.rhcloud.com/hello/?xyz
You can verify that by checking in your browser dev tools and seeing what URL the ajax call is actually requesting. Also note that in the flask handler you would then need to check for request.query_string to get the data, because <name> parameter would be empty.
Using the guidelines provided by Alex G Rice and the answers here Python Flask how to get parameters from a URL? I found out how to pass the data directly as following:
The Ajax call:
$.ajax({
type:"GET",
dataType: "json",
data:{'name':'Payam'},
url: "http://mypythonapp-spacepirate.rhcloud.com/hello/",
success: function(data){
buf1=data;
console.log(data);
}
})
The python file:
#app.route('/hello/', methods=['GET','POST'])
def hello_world(name=None):
buf1 = request.args.get('name')
str = {'key':'Hello World!', 'q':buf1}
#out = {'key':str}
res = json.dumps(str)
return res
This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 5 years ago.
I have run into a problem with my javascript/python script. What I am trying to do is pass a string to python flask so I can use it later. When I click the button to send the string, there are no errors but nothing happens. I am basically a self taught coder so I apologise if my script it not properly formatted!
Javascript:
$('#button').click(function() {
$.ajax({
url:"/",
type: 'POST',
data: data,
...
Python Flask:
from flask import Flask
from flask import request
from flask import render_template
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def home():
if request.method == "POST":
string = request.args.get(data)
print(string)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
I want to be able to see the string printed to either the console or the command prompt, I assume print() is the right way to do this?
Any help would be welcome, thank you :)
You can make an ajax POST request like this:
$.ajax({
url: "/",
method: "POST",
data: { paramter : value },
});
The data send over this POST request can be accessed in flask app withrequest.form['parameter']
If you are sending raw json data, you can access the data by request.json['parameter']
$.ajax({
url: "/",
method: "POST",
data: JSON.stringify("{'paramter': 'value'}"),
contentType: 'application/json;charset=UTF-8'
});
And this should work.
What you want is in request.data.
request.args contains parameters in the URL.
Check this out for more details. http://flask.pocoo.org/docs/0.11/api/#incoming-request-data
If you data object in Ajax is json then you can use request.get_json()
If it is form data of key value then you can request.form.get('data') but your ajax should be
$('#button').click(function() {
$.ajax({
url:"/",
type: 'POST',
data: {data: 'mystring'},
I have been having problems with getting AJAX to post JSON correctly. The application is intended to be hosted on Google App Engine. But what I have does not post data.
Python
mainPage = """
<html>
html is included in my python file.
</html>
"""
class JSONInterface(webapp2.RequestHandler):
def post(self):
name =self.request.get('name')
nickname =self.request.get('nickname')
callback = self.request.get('callback')
if len(name) > 0 and len(nickname) >0:
newmsg = Entry(name=name, nickname=nickname)
newmsg.put()
if len(name)>0:
self.response.out.write(getJSONMessages(callback))
else:
self.response.out.write("something didnt work")
def get(self):
callback = self.request.get('callback')
self.response.out.write(getJSONMessages(callback))
This handler is meant to handle the Ajax calls from the web app. I am unsure if I need javascript to be associated with my main page in order to do so, as I haven't found information on it yet with my searches.
Javascript
$(document).ready( function() {
$("#post").bind('click', function(event){
var name = $("#name").val();
var nickname = $("#nickname").val();
postData = {name: name, nickname: nickname, callback: "newMessage"};
$.ajax({
type: "POST",
url: "http://localhost:27080/json",
data: postData,
dataType: "json",
done: function() {
// Clear out the posted message...
$("#nickname").val('');
},
fail: function(e) {
confirm("Error", e.message);
}
});
// prevent default posting of form (since we're making an Ajax call)...
event.preventDefault();
});
The Javascript for the post
Can someone advise me on how I could resolve the problem I am having. Thanks for the time and help.
Did you ask the same question yesterday and then delete it? I swear I just answered the same question.
You're not sending your data as a JSON string. If you want to send as JSON, you need to encode data as a JSON string, or else you're just sending it as a query string.
data: JSON.stringify(postdata),
HOWERVER, your request handler is actually processing the request properly as query string instead of JSON, so you probably don't want to do that.
For starters, the ajax call is pretty close. The full path
"http:://localhost:27080/json"
is not necessary, the relative path will work, but that is not the problem.
Your callback, as it stands, will work as 'success':
success: function(response) {
alert(response);
// Clear out the posted message...
$("#nickname").val('');
}
However, this callback is being phased out in favor of other methods. 'Done' should be chained like so:
$.ajax({
type: "POST",
url: "/json",
data: postData,
dataType: "json"
}).done(function(data){
console.log(data);
});
Also, there might be problems on the server. If you use some logging, you will see that the data is indeed being sent to the server.
import json ## we'll get to this below
import logging
class JSONInterface(webapp2.RequestHandler):
def post(self):
name = self.request.get('name')
logging.info(name) ## will print the value of 'name'
Unless your python function getJSONMessages(callback) is returning a json object, your callback will not be called, even after you add the response parameter.
In your python code:
import json
import logging
class JSONInterface(webapp2.RequestHandler):
def post(self):
callback = self.request.get('callback')
logging.info(callback) # will print correctly
self.response.out.write(json.dumps(callback))
Using the json.dumps method encodes the passing object to json, which is what your ajax object is looking for.