1

I'm working with flask and handsontable. I'm interested in dynamically creating data and then passing it to a view for display with handsontable.

So far I have :

@app.route('/mv')
def my_view():

    pq = my_object()
    for p in pq:
        print str(p._data)

    return render_template('my_view.html', page_title = 'nothing yet')

if __name__ == '__main__':
    app.run()

The print statement generates a dictionary of keys values for each object that looks like:

 {u': False, 'delete_at': 1438759341.674, 'id': 43, 'fa': 0, 'created_at': 1438701741.674 }
 {u': False, 'delete_at': 1438759341.675, 'id': 44, 'fa': 0, 'created_at': 1438701741.675 }
 {u': False, 'delete_at': 1438759341.675, 'id': 47, 'fa': 0, 'created_at': 1438701741.675 }

I'd like to pass this data in to the view, preferably as JSON. How can I do this?

user1592380
  • 34,265
  • 92
  • 284
  • 515
  • The question is how to format a dictionary to JSON? If so, this might help: http://stackoverflow.com/questions/14661051/convert-python-dictionary-to-json-array – cnluzon Aug 04 '15 at 15:54

1 Answers1

6

You simply add the named parameter to the render_template call.

import json

@app.route('/mv')
def my_view():

    pq = my_object()

    # put all of the data into a list
    data = [p._data for p in pq]

    # render the template with our data
    return render_template('my_view.html', page_title = 'nothing yet', data=data)

if __name__ == '__main__':
    app.run()

Then you can access the value of data in your template (I'm assuming you're passing it into javascript).

<html>
<body>
    <script>
        var data = JSON.parse('{{ data | tojson }}');
        // do stuff with the data
    </script>
</body>
</html>
Brobin
  • 3,241
  • 2
  • 19
  • 35