下面是我的烧瓶代码。我正在连接到sqlite数据库,获取一些数据并制作pandas数据帧并将其转换为 CSV 并尝试将其传递给d3.js
import sqlite3
import pandas as pd
from flask import *
app = Flask(__name__)
@app.route("/new_graph",methods = ['GET','POST'])
def new_graph():
connection = sqlite3.connect('recruit.db')
query = "select * from customers"
//bunch of dataframe calculations using pandas
data = final_df.to_csv(sep=',')
print (data)
return render_template('new_display.html',data=data)
if __name__ == "__main__":
app.run(app.run( port=8069),debug=True)
也尝试了,
@app.route("/new_graph",methods = ['GET','POST'])
def new_graph():
if request.method == 'POST':
connection = sqlite3.connect('recruit.db')
query = "select * from customers"
//bunch of dataframe calculations using pandas
data = final_df.to_csv(sep=',')
return data
return render_template('new_display.html')
以下是 html :
<!DOCTYPE html>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
d3.csv("/new_graph", function(data) { //recommended way of passing csv
console.log(data[0]);
});
</script>
</body>
当我运行它时,它运行正常并且csv被打印出来:
127.0.0.1 - - [02/May/2017 17:52:12] "GET /new_graph HTTP/1.1" 200 -
,Home_Owners,Home_renters,Ethinicity
0,1229,24,Asian
1,9856,584,Black
2,793,11,Chinese
3,8681,351,Hispanic
4,256,6,American Indian
5,141,5,Japanese
6,23855,449,Other
7,4,0,Portuguese
8,39284,611,White
127.0.0.1 - - [02/May/2017 17:52:17] "GET /new_graph HTTP/1.1" 200 -
但是 console.log 打印出一个奇怪的输出:
Object {<!DOCTYPE html>: ""}
无法弄清楚,我哪里出错了。
答案 0 :(得分:0)
您将csv数据传递给模板文件。端点new_graph
返回html而不是您想要的csv数据。您可以直接返回csv数据。