如何使用flask.jsonify和在flask路由中呈现模板 [英] How to use flask.jsonify and render a template in a flask route

查看:282
本文介绍了如何使用flask.jsonify和在flask路由中呈现模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以渲染模板并在同一路径中使用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?

推荐答案

  1. 如果在不同情况下需要在一条路径中返回不同的响应对象:render_template返回已转换为有效Responseunicodejsonify已经返回Response的对象,因此可以同时使用在同一条路线上:

  1. 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))

  • 如果需要在模板中呈现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路由中呈现模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆