Is it possible to render a template and use flask.jsonify
in the same route?
@app.route('/thankyou')
def thankyou():
db = get_db()
summary_cursor = db.execute('SELECT * FROM orders JOIN order_items USING (transaction_id) WHERE orders.transaction_id = (SELECT MAX(transaction_id) FROM orders)')
summary = summary_cursor.fetchall()
data = map(list, summary)
print data
return render_template('thankyou.html', summary = json.dumps(data))
Right now I am using json.dumps
for serializing my data, but it does some weird stuff to it. I would like to use jsonify
, because when I do this I get a really pretty output that seems better to work with:
@app.route('/thankyou')
def thankyou():
db = get_db()
summary_cursor = db.execute('SELECT * FROM orders JOIN order_items USING (transaction_id) WHERE orders.transaction_id = (SELECT MAX(transaction_id) FROM orders)')
summary = summary_cursor.fetchall()
data = map(list, summary)
print data
return jsonify(summary = data)
Is there any way to combine the two?
If you need return different response objects in one route for different cases: render_template
return unicode
that transform to valid Response
and jsonify
return already Response
object, so you can use both in same route:
@app.route('/thankyou')
def thankyou():
db = get_db()
summary_cursor = db.execute('SELECT * FROM orders JOIN order_items USING (transaction_id) WHERE orders.transaction_id = (SELECT MAX(transaction_id) FROM orders)')
summary = summary_cursor.fetchall()
data = map(list, summary)
print data
if request.args['type'] == 'json':
return jsonify(summary = data)
else:
return render_template('thankyou.html', summary=data))
If you need render json in template: you can use safe tojson
filter in template. See my another answer: https://stackoverflow.com/a/23039331/880326.
If you need return json with rendered template values: you can implicitly render each template and set value for response dict or list, then just use jsonify.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With