I'm trying to load my json response into my template but when i check it into my console returns undefended !
#login_required
def booking_detail_lists(request,id):
obj = get_object_or_404(Booking.objects.annotate(no_persons=Count('takes_by')),id=id)
bookingvisitors = BookingVisitor.objects.filter(booking=obj)
doc = Document.objects.filter(booking=obj)
documents = []
for i in doc:
documents.append({
'source':i.docs.url
})
visitors = []
for i in bookingvisitors:
visitors.append({
'full_name':i.visitor.full_name,
'reason':i.reason,
'check_in_vis':i.check_in_vis.strftime("%Y-%m-%dT%H:%M"),
'check_out_vis':i.check_out_vis.strftime("%Y-%m-%dT%H:%M"),
'admin':i.admin.username,
'date':i.date.strftime("%Y-%m-%dT%H:%M")
})
data = {
'check_in':obj.check_in.strftime("%Y-%m-%dT%H:%M"),
'check_out':obj.check_out.strftime("%Y-%m-%dT%H:%M"),
'taker':obj.taker,
'phone':obj.phone,
'no_person':obj.no_persons,
'id':obj.id,
'takes_by':visitors,
'images':documents,
}
json_data = json.dumps(data)
return render(request,'booking/booking_detail.html',{'data':json_data,'obj':obj,'id':obj.id})
urls.py
path('ajax/booking/<int:id>',booking_detail_lists , name='booking_detail_lists'),
my html template and ajax
$.ajax({
type:'GET',
url:"{%url 'booking:booking_detail_lists' id=2222 %}".replace(/2222/,parseInt({{id}})),
success:function(data){
console.log(data.data)
}
})
<!--some html tags-->
but in the browser console returns undefinedbut when i just type {{data}} it show as i expected ?! thank you for your recommendation ..
in the function booking_detail_lists, you are returning render('<template_name>', {<Data for rendering in the template>})...
When you're calling this URL with ajax, actually the template booking_detail.html is returned, which is not in the json format, but the html one.. And this response doesn't have property data (which you're calling with data.data)..
JsonResponse
For the json response from django view, you need to use JsonResponse from django.http
Change your function to include this
# ...Rest Imports
from django.http import JsonResponse
#login_required
def booking_detail_lists(request, id):
# ...Processing and generation of data
return JsonResponse({'data':json_data,'obj':obj,'id':obj.id})
I am new to web development and I am stuck in a process that I need to render the same template with different values(in data shown in code) during 'POST' and 'GET'.
In my terminal, both get and post are invoked by the print statement in the python.
Majority of the code is taken from the Record voice with recorder.js and upload it to python-flask server, but WAV file is broken
#app.route("/", methods=['GET'])
def index_GET():
print('data in get',data)
print('GET IS INVOKED')
return render_template("index.html",q = "hello world",data = 8)
#app.route("/", methods=['POST'])
def index_POST():
f = request.files['audio_data']
basepath = os.path.dirname(__file__)
x = str(datetime.datetime.now()).replace(" ", "").replace(":","").replace(".","")+'.wav'
#upload to database folder uploads
with open(basepath+'/uploads/'+x, 'wb') as audio:
f.save(audio)
print("POST IS INVOKED")
print(data)
print('-'.center(100,'-'))
return render_template("index.html",q = "hello world",data = 1000)
Have the same route handle both methods, then use an if statement to do the correct thing:
#app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# Do some processing
return render_template('index.html', data = 'some value')
elif request.method == 'GET':
return render_template('index.html', data = 'some other value')
I have a function that analyzes a CSV file with Pandas and produces a dict with summary information. I want to return the results as a response from a Flask view. How do I return a JSON response?
#app.route("/summary")
def summary():
d = make_summary()
# send it back as json
A view can directly return a Python dict or list and Flask will call jsonify automatically.
#app.route("/summary")
def summary():
d = make_summary()
return d
For older Flask versions, or to return a different JSON-serializable object, import and use jsonify.
from flask import jsonify
#app.route("/summary")
def summary():
d = make_summary()
return jsonify(d)
jsonify serializes the data you pass it to JSON. If you want to serialize the data yourself, do what jsonify does by building a response with status=200 and mimetype='application/json'.
from flask import json
#app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
status=200,
mimetype='application/json'
)
return response
Pass keyword arguments to flask.jsonify and they will be output as a JSON object.
#app.route('/_get_current_user')
def get_current_user():
return jsonify(
username=g.user.username,
email=g.user.email,
id=g.user.id
)
{
"username": "admin",
"email": "admin#localhost",
"id": 42
}
If you already have a dict, you can pass it directly as jsonify(d).
If you don't want to use jsonify for some reason, you can do what it does manually. Call flask.json.dumps to create JSON data, then return a response with the application/json content type.
from flask import json
#app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
mimetype='application/json'
)
return response
flask.json is distinct from the built-in json module. It will use the faster simplejson module if available, and enables various integrations with your Flask app.
To return a JSON response and set a status code you can use make_response:
from flask import jsonify, make_response
#app.route('/summary')
def summary():
d = make_summary()
return make_response(jsonify(d), 200)
Inspiration taken from this comment in the Flask issue tracker.
As of version 1.1.0 Flask, if a view returns a dict it will be turned into a JSON response.
#app.route("/users", methods=['GET'])
def get_user():
return {
"user": "John Doe",
}
If you want to analyze a file uploaded by the user, the Flask quickstart shows how to get files from users and access them. Get the file from request.files and pass it to the summary function.
from flask import request, jsonify
from werkzeug import secure_filename
#app.route('/summary', methods=['GET', 'POST'])
def summary():
if request.method == 'POST':
csv = request.files['data']
return jsonify(
summary=make_summary(csv),
csv_name=secure_filename(csv.filename)
)
return render_template('submit_data.html')
Replace the 'data' key for request.files with the name of the file input in your HTML form.
Flask 1.1.x supports returning a JSON dict without calling jsonify. If you want to return something besides a dict, you still need to call jsonify.
#app.route("/")
def index():
return {
"api_stuff": "values",
}
is equivalent to
#app.route("/")
def index():
return jsonify({
"api_stuff": "values",
})
See the pull request that added this: https://github.com/pallets/flask/pull/3111
I use a decorator to return the result of jsonfiy. I think it is more readable when a view has multiple returns. This does not support returning a tuple like content, status, but I handle returning error statuses with app.errorhandler instead.
import functools
from flask import jsonify
def return_json(f):
#functools.wraps(f)
def inner(**kwargs):
return jsonify(f(**kwargs))
return inner
#app.route('/test/<arg>')
#return_json
def test(arg):
if arg == 'list':
return [1, 2, 3]
elif arg == 'dict':
return {'a': 1, 'b': 2}
elif arg == 'bool':
return True
return 'none of them'
Prior to Flask 0.11, jsonfiy would not allow returning an array directly. Instead, pass the list as a keyword argument.
#app.route('/get_records')
def get_records():
results = [
{
"rec_create_date": "12 Jun 2016",
"rec_dietary_info": "nothing",
"rec_dob": "01 Apr 1988",
"rec_first_name": "New",
"rec_last_name": "Guy",
},
{
"rec_create_date": "1 Apr 2016",
"rec_dietary_info": "Nut allergy",
"rec_dob": "01 Feb 1988",
"rec_first_name": "Old",
"rec_last_name": "Guy",
},
]
return jsonify(results=list)
In Flask 1.1, if you return a dictionary and it will automatically be converted into JSON. So if make_summary() returns a dictionary, you can
from flask import Flask
app = Flask(__name__)
#app.route('/summary')
def summary():
d = make_summary()
return d
The SO that asks about including the status code was closed as a duplicate to this one. So to also answer that question, you can include the status code by returning a tuple of the form (dict, int). The dict is converted to JSON and the int will be the HTTP Status Code. Without any input, the Status is the default 200. So in the above example the code would be 200. In the example below it is changed to 201.
from flask import Flask
app = Flask(__name__)
#app.route('/summary')
def summary():
d = make_summary()
return d, 201 # 200 is the default
You can check the status code using
curl --request GET "http://127.0.0.1:5000/summary" -w "\ncode: %{http_code}\n\n"
The answer is the same when using Flask's class-based views.
from flask import Flask, request, jsonify
from flask.views import MethodView
app = Flask(__name__)
class Summary(MethodView):
def get(self):
d = make_summary()
return jsonify(d)
app.add_url_rule('/summary/', view_func=Summary.as_view('summary'))
if its a dict, flask can return it directly (Version 1.0.2)
def summary():
d = make_summary()
return d, 200
To serialize an object, use jsonify from flask module to jsonify the object, a dictionary gets serialized by default. Also, if you're dealing with files you can always use make_response.
I like this way:
#app.route("/summary")
def summary():
responseBody = { "message": "bla bla bla", "summary": make_summary() }
return make_response(jsonify(responseBody), 200)
I am trying to call the function ssl_verify from my html template . But it gives 404 error. Can anyone help me with this? Where i am wrong ?
#views.py
def ssl_verify( request , dns, port ):
if request.is_ajax():
result = dns + port
return result
#urls.py
url(r'ssl_verify/(\d+)/(\d+)/$', views.ssl_verify,name='ssl_verify'),
#script in html
function verify()
{
dns = document.getElementById("dns1").value;
port = document.getElementById("port1").value;
$.post('ssl_verify/'+dns+'/'+port+'/', function (data) {
alert (data) ;
});
}
Your urls.py must contain (replace the regexp line)
url(r'^ssl_verify/(?P<dns>[^/]+)/(?P<port>[^/]+)/$','views.check_ssl'),
or if you import:
from views import check_ssl
....
url(r'^ssl_verify/(?P<dns>[^/]+)/(?P<port>[^/]+)/$','check_ssl'),
and your views:
from django.http import HttpResponse
def check_ssl( request , dns, port ):
if request.is_ajax():
message = str(dns)+str(port)
return HttpResponse(message)
else:
return HttpResponse('/faulthandler') # declare in urls if needed
I'm now working to develop google app engine using flask framework i have create a template with different control i need no to call function in python from my html where i catch the button trigger by ajax script the html code as follow
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" ></script>
<br>
<form action="" method="post" >
<div id ="par_input" ><table> <tr> <td><textarea id ="equation" rows="2" cols="60"></textarea> <input id ="insert" type="button" onclick="insert_fun()" value="Insert" > <!-- -->
</form>
</div>
<script type="text/javascript">
function insert_fun(){
//window.alert("Tariq work !");
$.ajax({
type: 'POST',
url: window.location.href + '/insert'
});
document.getElementById("equation").value = "{{ TARIQ_ID }}";
}
</script>
</html>
and my python code is
from flask import Flask #import the Flask class.
from flask import make_response
from flask import render_template
from flask import request
from flask import session
from flask.kvsession import KVSessionExtension
from flask import abort
from flask import jsonify
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
APPLICATION_NAME='application test '
app = Flask(__name__)
#app.route('/', methods=['GET'])
def index():
"""Initialize a session for the current user, and render index.html."""
TARIQ_ID = 'inside index function'
# serving it.
response = make_response(
render_template('tariq.html',
APPLICATION_NAME=APPLICATION_NAME,
TARIQ_ID=TARIQ_ID))
response.headers['Content-Type'] = 'text/html'
return response
#app.route('/', methods=['POST'])
def insert(self = webapp.RequestHandler):
TARIQ_ID = 'In Python Code Function__INSIDE RESPONSE___===='
response = make_response(
render_template('tariq.html',
APPLICATION_NAME=APPLICATION_NAME,
TARIQ_ID=TARIQ_ID))
response.headers['Content-Type'] = 'text/html'
return response
class MyHandler(webapp.RequestHandler):
def get(self):
TARIQ_ID = 'In Python Code Function__INSIDE get===='
self.response.out.write(unicode(
template.render('tariq.html',
TARIQ_ID)))
def post(self):
TARIQ_ID = 'In Python Code Function__INSIDE post===='
self.response.out.write(unicode(
template.render('tariq.html',
TARIQ_ID)))
def main():
#app.debug = True
#app.run(host='0.0.0.0', port=4567) #we use the run() function to run the local server with our application
app = webapp.WSGIApplication([
(r'.*',MyHandler)], debug=True)
wsgiref.handlers.CGIHandler().run(app)
if __name__ == '__main__':
main()
but the python function dose not return the updated value of TARIQ_ID also it dose not make any response please your help
I don't know Flask so this is just a guess, but do you need to change this:
#app.route('/', methods=['POST'])
def insert(self = webapp.RequestHandler):
to this:
#app.route('/insert', methods=['POST'])
def insert(self = webapp.RequestHandler):
A callback function is needed in the Javascript function insert_fun() in the $.ajax() call.
The examples in https://api.jquery.com/jQuery.ajax/ show '.done(some_callback_function)' after the $.ajax() call.