Difficulty accessing json file with d3 and bulb

I use Flask as a web framework, and I am trying to implement the first example from Mike Dewar's book β€œGetting Started with D3”. I have a Python script called run.py and two templates/ and static/ directories containing index.html and service_status.json , respectively. Unfortunately, my code does not transmit data at all, and it does not create any blatant 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.

+6
source share
3 answers

If the JSON file does not change, 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 JavaScript path to '/static/service_status.json'

+6
source

Static files, such as your json document, are served by default from a different directory from the templates - default is "static"

You do not need to use the url_for call in your view, you can use it in your template:

 d3.json("{{ url_for('static', filename='service_status.json') }}",draw); 

So, to summarize: 1) Move your json document to a static folder (by default, a static folder with the side of your templates folder) and 2) use url_for to call in your template to get the correct URI for your json document.

If you want to use a folder other than static, you can change it by passing static_folder to the Flask object constructor

+3
source

It seems you are getting a status code of 304, as you mentioned in previous comments. I see that your JSON has the following date / time:

 "Date": [ "12/15/2011" ], "Time": [ " 7:35AM" ], 

I am not 100% sure, but this may help:

http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#if-modified-since

Basically, he says that

"This request header is used with the GET method to make it conditional: if the requested document has not changed since the time specified in this field, the document will not be sent, and 304 will not be changed instead of the response. The format of this field is the same as the Date format:"

So, maybe you can check the timestamp for JSON and maybe just make a new save?

0
source

All Articles