I am pretty sure, i am messing up this.
I do ajax request to get some informations of an object.
$.ajax({
url: "/get_obj_ajax/",
type: "get",
data: {id:id}
}).done(function(data){
if(data!='bad'){
data = data.split('°');
var objtitle = data[0];
var objcontent = data[1];
..
});
and in django views:
def get_obj_ajax(request):
if request.method == "GET":
obj= MyModel.objects.get(id=int(request.GET.get('id')))
data = obj.title + '°' + obj.content
return HttpResponse(data)
return HttpResponse('bad')
this is what I normally do. but today while I was eating my lunch, I thought, there must be some more professional approach for this.. because i feel like this is too dumb code. and if suddenly content of my obj has something with ° in it, the parsing goes wrong.
.. any guidance will be appreciated.
you can return json data:
def get_obj_ajax(request):
import json
data={"issuccess": 'no'}
if request.method == "GET":
obj= MyModel.objects.get(id=int(request.GET.get('id')))
data = {"issuccess": 'yes',"title":obj.title ,"content": obj.content}
return HttpResponse(json.dumps(data), content_type="application/json")
in templates:
if(data.issuccess == 'yes'){
var objtitle = data.title;
var objcontent = data.content;
}...
Related
The call is currently happening via a Flutter application which makes a multi-part POST request.
Flutter Code
var request = http.MultipartRequest(
'POST',
Uri.parse('https://techfarmtest.herokuapp.com/upload'),
);
Map<String, String> headers = {"Content-type": "multipart/form-data"};
request.files.add(
http.MultipartFile(
widget.selectedImage.toString(),
widget.selectedImage.readAsBytes().asStream(),
widget.selectedImage.lengthSync(),
filename: widget.selectedImage.path.split('/').last,
),
);
request.headers.addAll(headers);
var res = await request.send();
http.Response response = await http.Response.fromStream(res);
var data = jsonDecode(response.body);
return data;
I intend to upload the image to the backend and then perform the prediction and retrieve the result in JSON format and the backend is scripted using Flask.
Flask Code
#app.route('/upload',methods=["POST"])
def upload_image():
if request.method == "POST":
imageFile = request.files['image']
fileName = werkzeug.utils.secure_filename(imageFile.filename)
print('\nRecieved File name : ' + imageFile.filename)
imageFile.save('./uploadedImages/' + fileName)
pred('./uploadedImages/fileName')
def pred(sampleFile):
model = load_model('./model.h5')
# model.summary()
sample_file = sampleFile
sample_img = image.load_img(sample_file,target_size = (256,256,3))
sample_img = image.img_to_array(sample_img)
sample_img = np.expand_dims(sample_img,axis=0)
prediction_arr = model.predict(sample_img)
result = {
'Sample' : str(sampleFile),
'Label' : str(class_names[prediction_arr.argmax()]),
'Confidence' : str(prediction_arr.max())
}
return jsonify(result)
The current issue I am facing is that I am making a bad request (400).This is a rough code (pseudocode) that I have figured out from various resources. Is there any way to go about it.
So, I figured it out by myself.
I will be attaching the code below for future references.
Flutter Code :
var request = http.MultipartRequest(
'POST',
Uri.parse('https://techfarmtest.herokuapp.com/upload'),
);
request.files.add(
await http.MultipartFile.fromPath('image', img.path),
);
var res = await request.send();
You can verify the POST request by using the below logs :
log('${res.statusCode}', name: 'POST-request-statusCode');
log('${res.reasonPhrase}', name: 'POST-request-status');
With respect to Flask :
#app.route('/upload',methods=["POST","PUT"])
def upload_image():
if request.method == "POST":
imageFile = request.files['image']
***you can perform any operation on the file you have recieved from the request now***
Thank you!
I'm trying to make a webpage in which you can specify a number of vectors, then insert modulus and angle for each one, and it will calculate the sum.
My code can do the calculation, but I can't properly display the result on my template.
views.py:
def sum_view(request):
if request.method == "POST":
message = ''
for j in range(2,12):
if not request.POST.get(f'vector_mod_{j}'):
num_vett = j - 1
result = Vector(0, 0)
for i in range(num_vett):
mod = float(request.POST.get(f'vector_mod_{i+1}'))
ang = float(request.POST.get(f'vector_ang_{i+1}'))
result += Vector(mod, ang)
message = f'Modulus: {result.modulus}, angle: {result.angle}°'
return JsonResponse({'message': message})
return render(request, 'vectsum/sum.html')
The problem is that when I submit I see a sort of firefox developer tools view with a menu including 'JSON', 'Raw Data', 'Headers', and the correct message displayed in a console-like way.
Here is the ajax part of my template:
$(document).on('submit','#calculate',function(e){
e.preventDefault();
$.ajax({
type:'POST',
headers: {'X-Requested-With': 'XMLHttpRequest'},
url:'/vectorialsum/',
data: $('#calculate').serialize()
success:function(data){
var mess = JSON.parse(data)['message']
document.getElementById('result').innerHTML += mess
}
})
});
Probably I don't get what return JsonResponse does, however how do I show the message in my page?
Edit:
maybe my question is not clear, I'll rephrase: how can I send back to ajax's success function the message variable?
All tutorias of how to use ajax with django said I should do something like this. But is that safe to do this? Cannot someone just change the values in the browser to some malicious SQL? If so, how to prevent it?
javascript
text = this.previousElementSibling.value;
parent = this.parentNode.id;
ajax.open('POST', '/post/comment/', true);
ajax.onreadystatechange = function(){
if(this.readyState == 4) {
reply = document.createElement("DIV");
reply.classList.add('post');
reply.innerHTML = this.responseText;
document.getElementById('comments').appendChild(reply);
}
}
ajax.setRequestHeader("X-CSRFToken", csrf_token);
ajax.setRequestHeader('Content-Type', 'application/json');
ajax.send(JSON.stringify({'text': text,'parent': parent}));
views.py
def post_comment(request):
if request.method == 'POST':
body = json.loads(request.body.decode('utf-8'))
parent = Post.objects.get(pk=body['parent'])
comment = Comment.objects.create(
author=request.user,
parent=parent,
group=parent.group,
text=body['text']
)
The API returns both JSON and also render the template and when i call $.getJSON it will only return that render template but not JSON value. I have tried this
if request.args['type'] == 'json':
return json.dumps(group)
else:
return render_template("/c.., summary=json.dumps(group))
but it says
bad request
Is there any way I can get that JSON value whenever I need it?
This is my view
#cms.route('/add/asset/<client_id>', methods=["GET"])
#login_required
def asset_add(client_id):
if int(current_user.id_) == int(client_id):
group = {}
group['id'] = []
group['pid'] = []
group['name'] = []
for index in range(len([r.id_ for r in db.session.query(Assetgroup.id_)])):
for asset in (Assetgroup.query.filter_by(parent_id=(index or ''))):
group['id'].append(asset.id_)
group['pid'].append(asset.parent_id)
group['name'].append(asset.name)
if request.args['type'] == 'json':
return json.dumps(group)
else:
return render_template("/cms/asset_add.html", action="/add/asset", asset=None,
client_id=client_id,
types=Type.query.all())
else:
return 'permission denied'
and this is my ajax request
$(document).ready(function () {
$('#group_id').click(function () {
$.getJSON(
'/add/asset/' + {{ client_id }},
function (data) {
$('#group_id').find('option').remove();
var len = data.id.length;
for (var i = 0; i < len; i++) {
var option_item = '<option value="' + data.id[i] + '">' + data.name[i] + "</option>";
$('#group_id').append(option_item);
}
}
);
});
});
You can add parameter in html call to get the json result...
i.e)
const Endpoint = '/add/asset/?'
$.getJSON(Endpoint, {type: 'json'}).done(function(data...)
I believe this is what you are looking for
http://flask.pocoo.org/docs/0.12/api/#flask.Request.is_json
That is a flask method that checks if the request is json
Then you can use jsonify still in flask to return json (you need to import it though)
from flask import jsonify
so your code becomes
if request.is_json:
return jsonify(group)
Hope you find that useful and more elegant
One of the easier ways to debug is just return json alone for a start to see how the response looks in a browser. So you can remove login required (assuming you are not yet in production), do not check if the request is_json, then call the api and see what it returns. So assuming your client id is 1
#cms.route('/add/asset/<client_id>', methods=["GET"])
def asset_add(client_id):
if int(current_user.id_) == int(client_id):
group = {}
group['id'] = []
group['pid'] = []
group['name'] = []
for index in range(len([r.id_ for r in db.session.query(Assetgroup.id_)])):
for asset in (Assetgroup.query.filter_by(parent_id=(index or ''))):
group['id'].append(asset.id_)
group['pid'].append(asset.parent_id)
group['name'].append(asset.name)
return jsonify(group)
Now you can visit http://yoursite.com/add/asset/1 to see your response
I'm trying to build a page where when the user presses a button a variable which initially is 0 increments with 1. This number is then sent asynchronously to the server by using jQuery AJAX.
What I have so far is:
In my __init__.py file:
def main(global_config, **settings):
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind = engine)
Base.metadata.bind = engine
config = Configurator(settings = settings)
config.include('pyramid_jinja2')
config.add_static_view('static', 'static')
config.add_static_view('scripts', 'scripts')
# Removed the other views
config.add_route("declare_usage", '/user/{user_id}/{address_id}/declare')
config.add_route("declare_usage_json",'/user/{user_id}/{address_id}/declare.json')
config.scan()
My HTML + Jinja2:
#Removed code for simplicity
<div id="button_add">Add</div>
{{val}}
My JS:
$(document).ready(function(){
var room = 0;
jQuery.ajax({type:'POST',
url: '/user/1/5/declare', #I use a direct user ID and a direct address ID as I'm not sure how to send this to JS from Pyramid ... yet :).
data: JSON.stringify(room),
contentType: 'application/json; charset=utf-8'});
$('#button_add').click(function(){
room = room + 1;
});
});
My view code:
#view_config(route_name = 'declare_usage', renderer = 'declara.jinja2')
#view_config(route_name = 'declare_usage_json', renderer = 'json')
def declara_consum(request):
#Removed code for simplicity
val = request.POST.get('room') #I get a "None value in my html" if I change to request.json_body -> I get an error that there is no json to be parsed.
return { 'val' : val }
What happens is that when I open the debugger the POST request is successful with no data and on the page I get 2 options for 'val':
None -> When I use val = request.POST.get('room')
Error ValueError: No JSON object could be decoded -> When I use val = request.json_body
Also, still can't get it to work if in my JS i change url to be /user/1/5/declare.json and/or data to {'room' : room}
Can somebody please point out what I'm doing wrong?
you don't need another route declare_usage_json, just need separate two function like this
#view_config(route_name = 'declare_usage', renderer = 'declara.jinja2')
def declara_consum(request):
# this will response to your jinja2
return { 'val' : val }
#view_config(route_name = 'declare_usage', xhr=True, renderer = 'json')
def declara_consum_ajax(request):
# this will response to your asynchronously request
val = request.POST.get('room')
return { 'val' : val }
when you send a request using ajax, this will goto the second function.
$.ajax({
type: 'POST',
url: '/user/1/5/declare',
data: {'room' : room},
dataType: 'json'
}).done(function(response){
// update your data at html
});