I am using Flask as a web framework, and I am trying to implement the first example from the book Getting Started with D3, by Mike Dewar. I have a Python script named run.py
and two directories, templates/
and static/
, containing index.html
and service_status.json, respectively. Unfortunately, my code is not rendering the data at all, nor is it producing any glaring errors.
This is what I have in run.py
:
#!/usr/bin/env python
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__=="__main__":
port = 5000
app.debug = True
app.run( port=port )
This is what I have in templates/index.html
:
<!DOCTYPE HTML>
<HTML>
<HEAD>
<META CHARSET="utf-8">
<SCRIPT SRC="http://d3js.org/d3.v3.min.js"></SCRIPT>
<SCRIPT>
function draw(data) {
"use strict";
d3.select("body")
.append("ul")
.selectAll("li")
.data(data)
.enter()
.append("li")
.text( function(d){
return d.name + ": " + d.status;
}
);
}
</SCRIPT>
<TITLE>MTA Data</TITLE>
</HEAD>
<BODY>
<H1>MTA Availability Data</H1>
<SCRIPT>
d3.json("{{ url_for( 'static', filename='service_status.json') }}",draw); // <---- BIG PROBLEM
</SCRIPT>
</BODY>
</HTML>
I am using Windows 7, Google Chrome, and Python 2.7.
If the JSON file is not going to change, then you should put it in the static
directory and use
from flask import url_for
url_for('static', filename='service_status.json')
For this to work, also change the path in the JavaScript to '/static/service_status.json'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With