Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulty accessing json file with d3 and flask

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.

like image 563
cjohnson318 Avatar asked Mar 18 '13 16:03

cjohnson318


1 Answers

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'

like image 105
Adam Obeng Avatar answered Sep 22 '22 05:09

Adam Obeng