S
S
Sergey Alekseev2018-01-18 13:36:46
JSON
Sergey Alekseev, 2018-01-18 13:36:46

Python how to render data with d3.js?

Good afternoon, you need to transfer data from the backend and accept it to d3.js.

import pymysql, json
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/get_data')
def index():
  #Подключаемся к MYSQL
    conn = pymysql.connect(host='localhost', port=3306, 
        user='root', passwd='nemate666', db='data_map')
    cursor = conn.cursor(pymysql.cursors.DictCursor)
  
  #Вытаскиваем данные и сериализуем в json
    query_data = cursor.execute("SELECT project_name, countryname, lendprojectcost FROM   data_load")
    for row in cursor:
        data = json.dumps(row)
        data_json = [data]


  #Закрываем соединение
    cursor.close()
    conn.close()

    return render_template('index.html', data_json=data_json)


if __name__=="__main__":
    app.run(host='0.0.0.0', port=5000, debug='true')

And accept d3.js
var width = 900, height = 600;

var projection = d3.geo.mercator();

      
var svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height);
var path = d3.geo.path().projection(projection);
var g = svg.append("g");

    d3.json("/get_data", function(error, data_json){
        g.selectAll("content")
      .data(topojson.object(data_json, data_json.objects.countries)
          .geometries)
  .enter()
    .append("content")
    .attr("d", path)
    });

Accordingly, the error data_json is undefined. How to accept d3.js data?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dimonchik, 2018-01-18
@dimonchik2013

do you return mimetype JSON?

A
agershun, 2019-10-29
@agershun

Now the function formats have changed, and json() returns a Promise with data that must be caught using the then() function:
d3.json("/get_data")
.then(function(data_json){
. . .
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question