2017-03-06 68 views
3

我目前正在學習使用Flask作爲python後端的d3.js,並且在this example後面顯示了在同一頁上使用不同數據集的兩個簡單圖表。Flags + d3.js:將多個數據集傳遞給html

我在嘗試進行以下修改:而不是使用CSV,我想從python後端傳遞json文件(該示例只是從兩個csv文件中讀取數據)。我該如何傳遞2個json數據集?我可以通過一個如下:

Python的後端

import flask... 

app = flask.Flask(__name__) 

@app.route("/") 
def index(): 
    return flask.render_template("index.html") 

@app.route("/data") 
def data(): 
    x = [1, 2, 3, 4, 5] 
    y = [1, 2, 3, 4, 5] 
    js = [{"x":x[i], "y":y[i]} for i in range(len(x))] 

    return json.dumps(js) 

的index.html

<script> 
d3.json("/data", function(data) ...) 
</script> 

我試圖寫另一個Python功能,像def data_bar返回一個單獨的JSON數據集,但無法讀取。從理論上說,我能通過在一個JSON數據集兩個數據集,如:

x = [1,2,3,4,5] 
y = [1,2,3,4,5] 
x1 = [10,20,30] 
y1 = [40,50,60] 

但是,如果所述第一組的結構域(x和y)和第二組(X1和Y1)AREN」此遇到的問題同樣的。例如第一組可以是「student_name」和「grade」,第二組可以是「class_name」和「average_grade」。

回答

0

呈現在通過一組數據:

return render_template("result.html",resultVarInHtml = myData) 

在通過多個數據集渲染:

return render_template("result.html",resultVarInHtml = myData, resultVarInHtml2 = myData2) 

現在,當我打開result.html

我可以使用此代碼顯示我的數據(假設一個關鍵值字典對象,但你明白了)

results.html

<!doctype html> 
<html> 
    <body> 
    <p>First Data Set</p> 
     <table border = 1> 
     {% for key, value in resultVarInHtml.iteritems() %} 

      <tr> 
       <th> {{ key }} </th> 
       <td> {{ value }} </td> 
      </tr> 

     {% endfor %} 
     </table> 
     <p>2nd Data Set</p> 
     <table border = 1> 
     {% for key, value in resultVarInHtml2.iteritems() %} 

      <tr> 
       <th> {{ key }} </th> 
       <td> {{ value }} </td> 
      </tr> 

     {% endfor %} 
     </table> 
    </body> 
</html> 

而且你會得到一個合適的表格,隊友。