user113531 user113531 - 7 months ago 32
Python Question

Injecting data into javascript with Python Flask

I am following the instructions from to create a sample chart. I have saved the main chunk of javascript locally, and am add the

<script src="/chart.js"></script>
tag in my html to reference it.

On my side, I am using python flask to render a html template containing the script.

@app.route('/view', methods=['POST', 'GET'])
def show_graph_view():
query= request.form['query']
data = get_current_data(query)
return render_template('graph.html', data=data)

I have a function to prepare some custom and current data I want to plot instead and I want the data to be available once the client brower loads. How do I add this data into the charts?


Assuming a globally accessible function, just call it in the module with the data converted to json on the server with the tojson and safe filters.

<script type=text/javascript> doSomethingWith({{ data|tojson|safe }}); </script>

It's a bit hard to follow the logic when you mix together server side templating and client side scripting like this. But sometimes you gotta do it.