是否可以渲染模板并flask.jsonify在同一路径中使用?
flask.jsonify
@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,因为执行此操作时,我得到一个非常漂亮的输出,似乎可以更好地与之配合使用:
json.dumps
jsonify
@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)
有什么办法可以将两者结合起来吗?
如果你需要在一条路由中针对不同的情况返回不同的响应对象:render_template将unicode转换转换为有效Response并jsonify返回已经存在的Response对象,因此可以在同一路由中使用这两种方法:
render_template将unicode
Response
@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))