S
S
Sergey Alekseev2018-01-24 08:15:56
JSON
Sergey Alekseev, 2018-01-24 08:15:56

Python Flask how to return json data in template and accept it in d3.js?

View that returns json

import pymysql, json
from flask import Flask, request, render_template, jsonify

app = Flask(__name__)


@app.route('/get_data')
def get_data():
    if request.method == 'GET':
        #Подключаемся к MYSQL
        conn = pymysql.connect(host='localhost', port=3306, 
            user='root', passwd='nemate666', db='data_mapping')
        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 = row

        return jsonify(data_json)


    return render_template('index.html')
    


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

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

I accept data from d3.js:
d3.json("/get_data", function(error, data_json){
    data_json.map(function(d) {
       return d.project_name
    })			          
});

I start the test server in Firefox and I get one object
{
"countryname": "Republic of Kenya",
"lendprojectcost": "300000000",
"project_name": "KENYA: NATIONAL URBAN TRANSPORT IMPROVEMENT PROJECT"
}
And a message in the browser console

Simple the text document contains no character encoding declaration. If the document contains characters that are not in the US-ASCII range, some browser configurations will display garbled text in the document. The character encoding of the file must be declared in the transfer protocol, or the file must use the Byte Order Indicator (BOM) as the encoding signature.

In fact, I do not accept data from d3.js. How to carry out this simple process. How to return json to html ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimonchik, 2018-01-24
@serj2000

and then the answer came?
Python how to render data with d3.js?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question