Loading Data Asynchronously in Python/Flask for d3.js
What you really need here is an API for accessing the data. If you're using flask already then Flask-Restful is a great option. You can set up a route like this:
from flask import Flaskfrom flask_restful import Resource, Api, reqparseapp = Flask(__name__)api = Api(app)class Data(Resource): def __init__(self): self.parser = reqparse.RequestParser() self.parser.add_argument('name', type=str, required = True) self.parser.add_argument('whatever', type=str, required = True) def post(self): args = self.parser.parse_args() #query your database here and do your stuff print(args['name']) print(args['whatever']) return {'data': 'your data here', 'other_information': 'more_stuff' }api.add_resource(Data, '/data')if __name__ == '__main__': app.run(debug=True)
and then you'll be able to pass variables that specify what data is needed to using either JSON, query strings, or a form. Flask-Restful is pretty smart and will figure out the method that you're using to send it automatically. Then you can return a dictionary which will be encoded using JSON. This should address your second issue of passing multiple variables back to the javascript.
An example of the corresponding javascript is here:
var xhr = new XMLHttpRequest();xhr.open("POST", "http://127.0.0.1:5000/data");xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');xhr.onload = function() { var dict = JSON.parse(xhr.responseText); console.log(dict['data']); console.log(dict['other_information']);};var request = JSON.stringify({'name':'my_name', 'whatever':'stuff'});xhr.send(request);