Loading data asynchronously in Python / Flask for d3.js

I have a python / flask application. In it, I have a page that queries the database many times to display data on the page. However, if I include this logic in view.py, where @ app.route (), then loading the page takes too much time. Then I show this data with d3.

My current setup is that I have a separate route from the view that calculates the data (for example, β€œ/ data” is the way to go). When you go to this path, it returns data in json format and loads

d3.json("/data", callback) 

It works great. My problem is that I need to fill in many different requests, and another path for each data set clutters my application and does not seem to comply with the DRY principle. Is there a better way to do this? I am also having difficulty transferring variables to javascript that runs d3 from python.

+6
source share
1 answer

Here you really need an API to access the data. If you are already using a jar then Flask-Restful is a great option. You can configure the route as follows:

 from flask import Flask from flask_restful import Resource, Api, reqparse app = 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 can pass in variables that indicate what data is needed to use JSON, query strings, or a form. Flask-Restful is pretty smart and will detect the method you use to send it automatically. You can then return the dictionary to be encoded using JSON. This should solve your second problem of passing multiple variables back to javascript.

An example of the corresponding javascript:

 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); 
+1
source

Source: https://habr.com/ru/post/969709/


All Articles