[英]How can I access dataframe values passed from a flask server to a js function in jinja template?
这是我的相关 flask 代码:
if request.method == 'POST':
symbol = request.form.get('symbol')
df = api.polygon.historic_agg_v2(symbol, 1, 'minute', _from='2020-06-30', to='2020-07-01').df
return render_template('graph.html', df = df.to_dict(orient='records'), symbol=symbol)
这是我的 dataframe 在 python 控制台上打印时的样子:
open high low close volume
timestamp
2020-06-30 09:29:00-04:00 86.500 86.500 86.2300 86.2300 406
2020-06-30 09:30:00-04:00 86.470 86.580 86.4700 86.5800 39602
2020-06-30 09:31:00-04:00 86.585 86.585 86.5239 86.5239 421
2020-06-30 09:32:00-04:00 86.630 86.630 86.5100 86.5650 1463
2020-06-30 09:33:00-04:00 86.740 86.790 86.7200 86.7900 876
这是一些获取df的模板代码:
var df = '{{df}}'
现在我将其记录到控制台并得到如下信息:
[
{
'open': 86.5,
'high': 86.5,
'low': 86.23,
'close': 86.23,
'volume': 406
},
{
'open': 86.47,
'high': 86.58,
'low': 86.47,
'close': 86.58,
'volume': 39602
},
{
'open': 86.585,
'high': 86.585,
'low': 86.5239,
'close': 86.5239,
'volume': 421
}, .... ]
为什么dataframe会这样变化,为什么timestamp会丢失? 另外,我想通过从 canvas.js 修改此 function 来访问这些 dataframe 值以绘制它们。 我的计划是迭代 Df 值,类似于它们如何迭代 CSV 的行。 这种方法可行吗?
function updateChart(csv) {
var csvLines = points = [];
csvLines = csv.split(/[\r?\n|\r|\n]+/);
for (var i = 0; i < csvLines.length; i++) {
if (csvLines[i].length > 0) {
points = csvLines[i].split(",");
dataPoints.push({
x: new Date(
//access timestamp value here
parseInt(points[0].split("-")[0]),
parseInt(points[0].split("-")[1]),
parseInt(points[0].split("-")[2])
),
y: [
//acces high low open close here
parseFloat(points[1]),
parseFloat(points[2]),
parseFloat(points[3]),
parseFloat(points[4])
]
});
}
}
chart.render();
}
}
在经历了一些挫折之后,我能够弄清楚,这是任何遇到这篇文章的人的答案。
我无法正确访问 dataframe 的原因是因为我没有将其正确转换为 json 格式。 为了做到这一点,我只添加了几行。
graph.html 文件:
var df = {{df|tojson}};
var jsonObj = eval('[' + df + ']');
应用程序.py
return render_template('graph.html', df = df.to_json(), symbol=symbol)
在 app.py 中,我将 dataframe 转换为 json 字符串,并在 app.py 收到 post 请求时将其传递给 graph.html。 然后在 graph.html 中,它将 df 转换为用于 JS/html 文件的格式。 此语法 {{var|tojson}} 特定于 jinja2,这是 flask 使用的模板引擎。 然后我把 json 字符串变成 json object。
然后读取数据并创建图形的数据点,我有 js function 如下:
function updateChart(jsonObj) {
var df = {{df|tojson}};
var jsonObj = eval('[' + df + ']');
for (var i = 0; i < 1000; i++) {
var timestamp = jsonObj[0].timestamp[i]
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setTime(timestamp);
console.log(d);
dataPoints.push({
x: d,
y: [
parseFloat(jsonObj[0].open[i]),
parseFloat(jsonObj[0].high[i]),
parseFloat(jsonObj[0].low[i]),
parseFloat(jsonObj[0].close[i])
]
});
}
chart.render();
} }
This graph is created using the canvas.js library, which uses another function in conjunction with updateChart to create a chart object and then passes the data from updateChart function to the chart object. 希望这对使用 Flask 和 JS 的其他人有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.