一尘不染

如何使用flask.jsonify和在Flask路由中呈现模板

flask

是否可以渲染模板并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,因为执行此操作时,我得到一个非常漂亮的输出,似乎可以更好地与之配合使用:

@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)

有什么办法可以将两者结合起来吗?


阅读 550

收藏
2020-04-08

共1个答案

一尘不染

如果你需要在一条路由中针对不同的情况返回不同的响应对象:render_template将unicode转换转换为有效Responsejsonify返回已经存在的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))
2020-04-08