Python user, learning some basic javascript:
I have created a simple flask app for demonstration. (For a quick test, I've put this example on Github: https://github.com/robertdavidwest/flask_d3_example)
dependencies:
- python=3.7.1
- flask=1.0.2
- flask-cors=3.0.7
and https://d3js.org/d3.v5.min.js
APP:
.
├── run.py
├── static
│ └── js
│ └── data.js
└── templates
└── index.html
I'm serving data from a flask app:
from flask import Flask, render_template, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/get-data")
def get_data():
return jsonify({"a": 1, "b": 2})
With the server running, if I navigate to http://127.0.0.1:5000/get-data then I see the data.
But when I try to use d3.json
to request the data from the front end, nothing seems to happen (I've tried logging the data and writing to a div):
d3.json("http://127.0.0.1:5000/get-data",
function(d){
console.log(d);
document.getElementById("d3-write-here").innerHTML = d;
})
Any guidance would be greatly appreciated.
Details of all code in simple app:
index.html:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="utf-8" />
<title>Simple Example</title>
</head>
<body>
<h2>Nothing much here</h2>
<div id="d3-write-here"></div>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="{{ url_for('static', filename='js/data.js') }}">
</script>
run.py:
from flask import Flask, render_template, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/get-data")
def get_data():
return jsonify({"a": 1, "b": 2})
if __name__ == '__main__':
app.debug = True
app.run()
static/js/data.js:
d3.json("http://127.0.0.1:5000/get-data",
function(d){
console.log(d);
document.getElementById("d3-write-here").innerHTML = d;
})