问题描述
是否可以渲染模板并在同一路径中使用flask.jsonify
?
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))
现在,我正在使用json.dumps
序列化我的数据,但是这样做有些奇怪.我想使用jsonify
,因为当我这样做时,我会得到一个非常漂亮的输出,似乎可以更好地与之配合使用:
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?
推荐答案
-
如果在不同情况下需要在一条路径中返回不同的响应对象:
render_template
返回已转换为有效Response
的unicode
和jsonify
已经返回Response
的对象,因此可以同时使用在同一条路线上:
If you need return different response objects in one route for different cases:
render_template
returnunicode
that transform to validResponse
andjsonify
return alreadyResponse
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))
如果需要在模板中呈现json:可以在模板中使用安全的tojson
过滤器.看到我的另一个答案: https://stackoverflow.com/a/23039331/880326 .
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.
如果您需要返回带有渲染模板值的json:您可以隐式渲染每个模板并为响应字典或列表设置值,则只需使用jsonify.
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.
这篇关于如何使用flask.jsonify和在flask路由中呈现模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!