我的烧瓶代码部分有问题 main.py
from flask import Flask, render_template, url_for
import pandas as pd
import json
app = Flask(__name__)
@app.route('/')
def home():
df = pd.read_csv('test.csv')
df = df.groupby('name')['marks'].sum()
j = df.to_json(orient='index')
return render_template("work.html",s=j)
if __name__ == "__main__":
app.run(debug=True)
,我想将j传递给我的javascript文件,看起来像那样 work.js
//pie chart
var s = {{ j|safe }};
var keys = [];
for(var k in s) keys.push(k);
var value = [];
for (var k in s) value.push(s[k]);
var data = [{
values: value,
labels: keys,
type: 'pie'
}];
var layout = {
height: 400,
width: 500
};
Plotly.newPlot('myDiv1', data);
work.html
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="navbar"><span>data representation with Plotly.js</span></div>
<div class="wrapper">
<div id="myDiv1"></div>
<script type="text/javascript" src={{ url_for('static', filename='work.js')}}>
</script>
</div>
</body>
</html>
如何将flask中的j变量传递给使用html页面呈现并显示正确内容的javascript文件中的s变量,或者说未显示任何图 谢谢
答案 0 :(得分:1)
您不能那样做。您必须在flask方法中返回该json并通过javascript制作一个ajax request。
from flask import jsonify
@app.route('/')
def home():
j = df.to_json(orient='index')
return jsonify(j)
我不知道烧瓶是否像Django一样具有JsonResponse
之类的东西。如果是,则应这样使用:return JsonResponse(j)
$.ajax({url: "your_url", success: function(result){
//result is what you returned from flask
}});