简体   繁体   中英

How to use flask.jsonify and render a template in a flask route

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?

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

  3. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM