shell
shell

Reputation: 1937

Dygraph is not defined, using Flask

I am using flask and trying to get the dygraph sample to work. Here is the sample code (2nd example from the tutorial page: http://dygraphs.com/tutorial.html):

<html>
<head>
<script type="text/javascript"
  src="dygraph-combined.js"></script>
</head>
<body>
<div id="graphdiv2"
  style="width:500px; height:300px;"></div>
<script type="text/javascript">
  g2 = new Dygraph(
    document.getElementById("graphdiv2"),
    "temperatures.csv", // path to CSV file
    {}          // options
  );
</script>
</body>
</html>

Here is my Flask code (I'm trying to use render_template()):

from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def render_plot():
    return render_template('sample.html')
if __name__ == '__main__':
    app.run()

When I run this through python firebug gives me the error "Dygraph is not defined." from the line g2 = new Dygraph(

Sample.html works in my folder, but it does not work when I try to access it from my url after running my flask code from python. My folders look like this:

FlaskStuff/main.py

FlaskStuff/templates/sample.html

FlaskStuff/templates/dygraph-combined.js (To load sample.html in my folder).

FlaskStuff/js/dygraph-combined.js

I am new to Flask. Similar answers did not help me to solve this problem.

Upvotes: 0

Views: 743

Answers (2)

novedevon
novedevon

Reputation: 33

You will also have to do a similar thing for the temperature.csv file. (I've placed it in the static folder)

"{{ url_for('static', filename='temperatures.csv') }}", // path to CSV file

Upvotes: 0

dirn
dirn

Reputation: 20729

Where is dygraph-combined.js located? It needs to be somewhere it can be served. You will most likely what to place it inside your static folder. It's a fairly common practice to group like files inside static (e.g., css, js).

Using this structure

static/
    js/
        dygraph-combined.js

you'll want to update sample.html as follows

<script type="text/javascript" src="{{ url_for('static', filename='js/dygraph-combined.js') }}"></script>

This will allow the Flask development server to serve the file. You'll also want to add a rule to your HTTP server to serve content from /static directly.

Upvotes: 1

Related Questions