Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

flask

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?

like image 642
metersk Avatar asked May 28 '14 03:05

metersk


1 Answers

  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.

like image 90
tbicr Avatar answered Oct 23 '22 11:10

tbicr