I have a Flask API with this endpoint :
#app.route('/classify/', methods=['POST'])
def classify():
data = request.get_json()
When I POST a request with python, eveything is fine.
But when I use Postman, I get :
<class 'werkzeug.exceptions.BadRequest'> : 400: Bad Request
I send the same Json with both (I copy/paste it to be sure). I am fairly confident the issue is caused by some "\t" in my json, which are escaped by python but not by Postman.
Is there a way to retrieve the raw json, and process it (escape what needs to be escaped) in the app ? Or another way to get the json ?
EDIT : This is a different question from the one you suggested as duplicate, because yours suggest to use get_json, which is the problem in my case.
Ok, so it turns out you can replace :
data = request.get_json()
By :
data = json.loads(request.data, strict=False) # strict = False allow for escaped char
requests.data contains the json in string format, so you can process the characters that needs to be escaped.
use request.data instead of request.get_json() if your data could be empty or a bad request will be raised!
All error about ajax and flask send data from templates for python file.
Recive all data of ajax json.
data = request.get_json("")
print(data)
return "success!"
Send data in ajax json.
$(document).on('click','#texthide',function(){
var text = $("#textVal").val();
var font = $("#font_text").val();
var color = $("#color_text").val();
var start_text = $("#start_text").val();
var end_text = $("#end_text").val();
var vid_id = new_d
console.log(text);
$.ajax({
url: '/videos/test_text',
type: 'POST',
contentType: 'application/json; charset=utf-8',
datatype: "json",
data: JSON.stringify(
{ text: $("#textVal").val(),
font: $("#font_text").val(),
color: $("#color_text").val(),
start_text: $("#start_text").val(),
end_text: $("#end_text").val(),
video_id: new_d
})
});
});
Related
This is my implementation,
full_url = url + '?' + params
req = urllib2.Request(full_url, params)
req.add_header('Content-Type', 'application/javascript')
req.add_header('Access-Control-Allow-Origin','*')
req.add_header('Accept', 'application/javascript')
req.add_header('x-lang', 'en')
req.add_header('x-app-version', '1.2.3')
req.add_header('x-consumer-key', 'abc')
req.add_header('x-source', 'web')
req.add_header('x-device-id', 'abc-2501015753736970469271537365900144030')
req.add_header('x-signature', signature)
req.add_header('X-Content-Type-Options', 'nosniff')
req.add_header('x-request-id', request)
req.add_header('x-timestamp', timeStamp)
response = urllib2.urlopen(req)
result = response.read()
result = result.decode('latin-1')
respjson = json.loads(result)
return respjson
Reading the output in ext.js
var script = document.createElement("script");
script.setAttribute("src", url);
script.setAttribute("type", "text/javascript");
script.setAttribute("id", trans.scriptId);
document.getElementsByTagName("head")[0].appendChild(script);
Thank you in advance.
Error shows in the browser "was loaded even though its MIME type (“application/json”) is not a valid JavaScript MIME"
[Error in the browser][1]
Short Answer:
Use JSONP instead of JSON in ExtJS.
Tons of additional information
better ways to retrieve a JSON from ExtJS
But this was not the question I assume.
Let's say you have your JSON and you are trying to populate a store.
Instead of injecting the JSON into the DOM, you could use:
Ext.StoreManager.get('storeId').load(JSON);
// or for the store of a grid
Ext.ComponentQuery.query('grid')[0].getStore().load(JSON);
// or for xtype main
Ext.first('main').getViewModel().set('initData', JSON);
All these methods would get the data into an ExtJS App
Retrieving Data
Getting Data into ExtJS typically would be done using
Ext.Ajax.request({
url: full_url,
header: ...
success: success_fn,
scope: this
})
Or directly in your model/store
I am making ajax call to flask function to get data using a token as following
#app.route("/questgen/results", methods = ['POST', 'GET'])
def fetch_results():
token = request.form.get('token')
print(token)
conn = sqlite3.connect("database.db" , timeout=20)
cur= conn.cursor()
select_query = '''SELECT processed, output_text
FROM results
WHERE token = token
'''
cur.execute(select_query)
records = cur.fetchall()
processed = ""
html = ""
for row in records:
processed = row[0]
html = row[1]
conn.close()
data = {'processed': processed, 'html' : html}
return redirect(url_for('questgen', data = data))
ajax call is as following
$.ajax({
type: "POST",
url: "/questgen/results",
data: { token: token },
datatype: "json",
success: function (data) {
if (data.processed == 1) {
$('#divresults').html(data.html);
$('#divresults').show();
hideMyModal();
clearInterval(saveInterval);
}
}
});
the complete is a bit lengthy it can be found in this gist the problem is that it returns
TypeError: The view function did not return a valid response. The
function either returned None or ended without a return statement.
even though I have tried same flask function as python function by using return data on the same database and it works. I have even tried to get token as function parameter but still it's not working. Can someone help with what am I doing wrong here? Thank you
The jQuery ajax call does not handle redirects automatically. You'll just get a response with a 301 or 302 status code. If you really need to have it redirect, you'll need to check for a 302 status return and make the call again with the changed data. It would be better if you could just do the redirection internally by calling the other function.
Try jsonify to return data
from flask import Flask, jsonify, request #import this
And then use this to return data
return jsonify({"res": data})
In ajax you will get your data in res
console.log(data.res) // your data
console.log(data.res.processed) // your if condition
Also check whether you need to parse response body or not
I get a confused error.
Its about swift data type.
there is my network demo:
func initRequst(HttpType: httpType,content:String,dic:Dictionary<String,Any>){
let data = try! JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
print(data)
switch HttpType {
case .post:
url = URL.init(string: "http://localhost:5000/" + content)
req = NSMutableURLRequest.init(url: url!)
req?.httpMethod = "POST"
req?.httpBody = data
case .get:
url = URL.init(string: "http://localhost:5000/" + content)
req = NSMutableURLRequest.init(url: url!)
req?.httpBody = data
req?.httpMethod = "GET"
}
}
And there is my flask server have received error and demo:
TypeError: 'NoneType' object is not subscriptable
#app.route('/userLogin',methods=["GET"])
def userLogin():
get_username = request.json['username']
get_password = request.json['password']
return jsonify({"uerId":databasePort.checkUserInformation(get_username,get_password)})
it seems that swift data sending type have not be identified.How to fix it? Thanks!
You could try setting the Content-Type header to application/json before sending the request in Swift. Then Flask will attempt to decode it and assign it to the request's json attribute:
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
Flask will set request.json only if the incoming request sets the content type to json, otherwise it will assume form encoded data which it will assign to request.form.
I know its a very basic question but after wasting my whole day I am asking this. I am just sending data using following AngularJS code to Django:
$http.post('/data/creation',
{
html: 'a'
}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(status);
console.log(data);
});
and in django:
#csrf_exempt
def snippets_post(request):
html = False
css = False
js = False
JSONdata = False
response = "You're looking at the results of question %s."
if request.method == 'POST':
try:
JSONdata = request.POST.get('data', False) # it was [] in actual
except:
JSONdata = 'ERROR'
return HttpResponse(JSONdata)
I am getting False as response, "by replacing data to html in POST.get result is same". I don't know whats going wrong here. Can any one help me here on this?
Thanks
Actually, when we send data from AngularJs using $http's POST, it sends the data with the content-type = "application/json" to the server. And Django doesn't understand that format. And so you can't get the sent data.
Solution is to change the content-type header by using following config:
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
}]);
I have a JAVASCRIPT array allPois which contains several pois objects with the structure below:
var poi = {
title: pois[x].title,
lat: pois[x].position.lat(),
lng: pois[x].position.lng(),
html: pois[x].html
};
This is the JAVASCRIPT function that calls my server:
function save(){
var jsonizedData = JSON.stringify({theArray:allPois});
jQuery.ajax({
type: 'POST',
url: 'http://localhost:8000/save',
contentType:'application/json; charset=utf-8',
dataType: 'json',
data: mydata,
async: true
});
}
This is function on the server side that process the request:
def save(request):
for object in request.POST:
my_data = simplejson.loads(object)
return none
What is the best way to encode/decode the parameter 'html' (that contains actually html code) so that it can be loaded properly in the server?
Since the value of the property .html is string, you don't need to do anything. JSON can handle string values all right. Any modifications by you will only make things worse.
Your problem is probably how you get the value from the text area. See this jsfiddle how special characters are handled.
But in modern browsers, no encoding/decoding is necessary at any step.
Oh, and make sure you clean the HTML to avoid XSS and other attacks.