I have a Flask application where I have a form that collects some user input. That input is then passed as JSON data via an AJAX call to a function in my Python script.
This function calls an API, gets some new data and then returns a redirect URL to the AJAX call. On success, AJAX then redirects to this new template with window.location.href.
I tried 'passing' the first view function, the_search, over to the second view function to then render the appropriate template but this didn't do the trick unfortunately. I've also tried setting the data as a session variable and then accessing it in the template but this doesn't seem to work either.
My issue
How can I access the variable 'response' within the redirected template, results.html?
AJAX script
...
$.ajax({
type: 'POST',
url: '/the_search',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function(data, status) {
window.location.href = data['website'];
},
error: function() {
console.log('there was an error');
}
})
...
Python script
#app.route('/the_search', methods=("POST", 'GET'))
def the_search():
data = json.loads(request.data)
lat = data['latitude']
longitude = data['longitude']
response = unirest.get("https://zilyo.p.mashape.com/search?latitude={}&longitude={}".format(lat, longitude),
headers={
"X-Mashape-Key": "k6HBYxvy88mshQ6Yg1xPVuv7Vg9Np1GZj7IjsnPxploykdpaHA",
"Accept": "application/json"})
session['search_results'] = response.body
return jsonify({'website': '/results'}), 200
#app.route('/results', methods=('POST', 'GET'))
def results():
#How can I pass the_search view function to here while still having access to the response data
print session['search_results']
return render_template('results.html')
Related
I'm trying to send some data from JQuery.ajax() to my python Flask server, JS code is:
let data = JSON.stringify({nickname: "AAA", password: "BBB"});
$.ajax({
async: true,
data: data,
dataType : "json",
contentType: "application/json",
method: "GET",
url: "/test_back",
success: function() {},
error: function() {}
});
Python code is:
#app.route("/test_back", methods=["GET", "POST"])
def test_back():
print(request)
data = request.get_json()
print(data)
return jsonify({})
And print(data) is writing None in console, so I can't read it as a dict.
When I change method: "GET" to method: "POST", it works just fine.
So: how do I send JSON from JQuery to Flask, using method GET, correctly?
First of all add conditional for flask methods get and post its good practices :D
if request.method == "POST":
if request.method == "GET":
also try return the data not the empty jsonfy
return data
not
return jsonify({})_
I am not able to retrieve data field of AJAX in python flask.
Its shows type error when I try to retrieve data. type and forwho are of array type. When I alert them in AJAX it works.
Here is my code,
// Ajax
$.ajax({
url: '/products',
data: JSON.stringify({'type':type,'forwho': forwho}),
contentType: "application/json; charset=utf-8",
type: 'POST',
success: function(response){
/*alert("success");*/
$("#content").html(response);
},
error: function(error){
/*alert("error");*/
console.log(error);
}
});
# app.py
#app.route('/products', methods =['POST', 'GET'])
def all_products():
if request.method == 'POST':
print("inside all products post")
type = json.loads(request.form.get('type'))
forwho = json.loads(request.form.getlist('forwho'))
print(type)
print(forwho)
when I print print(request.args.get('typearr')) in all_products() it returns None
type =request.json['type']
forwho = request.json['forwho']
Flask automatically parses JSON when having application/JSON in your request.
This solution finally worked for me.
ajax:
data: JSON.stringify({'typearr':type,'forwho':forwho})
``````````````````
app.py:
#import ast
``````````````
data = request.get_data()
data = ast.literal_eval(data.decode("UTF-8"))
typearr = data['typearr']
forwho = data['forwho']
I am trying to test a very simple Express App. I have my Express set up in a typescript file as follows to respond with the body of the request that it receives:
app.listen(3000, () => console.log('Server running on port 3000'))
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json())
app.get('/test', (req, res) => {
res.send(req.body)
});
I am trying to call this endpoint in a python file as follows
testUrl = 'http://localhost:3000'
path = '/test'
header = {
'Content-Type': 'application/json',
}
body = {
'artistName': 'test',
}
response = requests.request(
method="GET",
url = testUrl + path,
params=header,
data=body,
)
print(response._content)
When I run the python file, all it prints out is a set of empty brackets, telling me that the body of the request it is receiving is empty. Why is the body empty if I am setting the data parameter to a populated json object? Am I using the wrong parameters? Thanks for the help!
I don't know what you mean to do with res.send(req.body) in your Express code, but req.body is not used for a GET request in Express. That's used for a POST or PUT.
Parameters for a GET request are put in the URL as part of the queryString and will appear in the req.query object in Express.
I think your mistake is in the request,
Because you are sending your header as params
I'm working on a flask web application in which the client posts data to the server in the form of:
{
"sess_id" : 1 ,
"annotations" :
[ {"tag_start" : "TIME","tag_end" : "TIME","tag" : "YOUR_TAG"}, {"tag_start" : "TIME","tag_end" : "TIME","tag" : "YOUR_TAG"}, {"tag_start" : "TIME","tag_end" : "TIME","tag" : "YOUR_TAG"}]
}
Here is the full Ajax post...
$.ajax({
url: 'http://127.0.0.1:5000/api/saveannotation',
type: 'POST',
headers: {'Content-Type' : 'application/json'},
data: {'sess_id' : $('#sessionid_area').val(),
'annotations': JSON.parse(annotations)},
success: function(data) { alert(data.status); }
});
so I can even see this on the api side, which is defined as such:
#sessionapis.route('/saveannotation', methods=['GET', 'POST'])
#login_required
def save_annotation():
rData = request.data
if request.method == 'GET':
return jsonify({'status' : 'success GET'})
else:
return jsonify({'status' : 'success'})
The issue is that data is a "byte" type, not a dict. I also can't call request.json or request.get_json(silent=True), it returns "400 bad request".
Here is a sample of what is in request.data:
b'sess_id=1&annotations%5B0%5D%5Btag_start%5D=2...
it appears to be url encoded for some reason. Values is also empty. If I choose to do something wild, like leave out the content-type = json; I can get a dict-like thing, but I have to access it very oddly. I don't get individual objects, but rather just flat access to all properties.
Any thoughts on how to just get the json parsed into a reasonable object?
Thanks for any hints!
Just passing a content-type header of JSON doesn't actually make the data itself into JSON. You either need to do that yourself, or tell jQuery to do so.
$.ajax({
url: 'http://127.0.0.1:5000/api/saveannotation',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({'sess_id' : $('#sessionid_area').val(),
'annotations': JSON.parse(annotations)}),
success: function(data) { alert(data.status); }
});
Now your data will be in JSON format and you can get it as a Python dict with request.get_json().
I have a data structure like this:
I'm try to send it to server by $.ajax:
$.ajax({
type: 'POST',
data: post_obj, //this is my json data
dataType: 'json',
url: '',
success: function(e){
console.log(e);
}
});
and I want get it in server by flask: title = request.form['title'] working fine!
But how do I get content ?
request.form.getlist('content') doesn't work.
This is the post data in firebug:
Thanks a lot :D
You are sending your data encoded as query string instead of JSON. Flask is capable of processing JSON encoded data, so it makes more sense to send it like that. Here's what you need to do on the client side:
$.ajax({
type: 'POST',
// Provide correct Content-Type, so that Flask will know how to process it.
contentType: 'application/json',
// Encode your data as JSON.
data: JSON.stringify(post_obj),
// This is the type of data you're expecting back from the server.
dataType: 'json',
url: '/some/url',
success: function (e) {
console.log(e);
}
});
On the server side data is accessed via request.json (already decoded):
content = request.json['content']
If you inspect the POST being submitted by jQuery, you will most likely see that content is actually being passed as content[]. To access it from the Flask's request object, you would then need to use request.form.getlist('content[]').
If you would prefer to have it passed through as content, you can add traditional: true to your $.ajax() call.
More details about this can be found in the 'data' and 'traditional' sections of http://api.jquery.com/jQuery.ajax/.