【发布时间】:2020-04-21 11:29:45
【问题描述】:
我对使用 Flask 和 Python 构建应用程序完全陌生。
我正在尝试创建 Google 柱形图,当我更改 Phython 文件中的数据时,它会动态变化。 我尝试了很多不同的方式,在stackoverflow上有描述,但它们不符合我的需求。
我对Javascript一无所知。
我的数据看起来像这个列表:
Status = [('active', '106297'), ('inactive', '236'), ('planned', '27453')]
@app.route('/test03')
def test03():
return render_template('chart.html', **globals())
我已经尝试将此列表转换为 JSON,但找不到正确的格式。
如果你能帮助我,那就太好了。 :)
更新:
from flask import Flask, render_template, request, jsonify, url_for
import gviz_api
# Creating the data
description = {"name": ("string", "Name"),
"salary": ("number", "Salary")}
data = [{"name": "Mike", "salary": 10000},
{"name": "Jim", "salary": 800},
{"name": "Alice", "salary": 12500},
{"name": "Bob", "salary": 7000}]
# Loading it into gviz_api.DataTable
data_table = gviz_api.DataTable(description)
data_table.LoadData(data)
# Create a JavaScript code string.
jscode = data_table.ToJSCode("jscode_data",
columns_order=("name", "salary"),
order_by="salary")
# Create a JSON string.
jsonData = data_table.ToJSon(columns_order=("name", "salary"),
order_by="salary")
print("Finish")
app = Flask(__name__)
# charts = GoogleCharts(app)
@app.route('/')
def test():
return render_template('chart.html', **globals())
if __name__ == '__main__':
# app.run(debug=True, host='192.168.43.183', port=800) # Home
还有 chart.html 文件:
{% extends 'base.html' %}
{% block head %}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// Define the chart to be drawn.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw the chart.
var chart = new google.visualization.ColumnChart(document.getElementById('myPieChart'));
chart.draw(data, null);
}
</script>
{% endblock %}
{% block body %}
<h1>Hello, this is my Columnchart-Test</h1>
<!-- Identify where the chart should be drawn. -->
<div id="myPieChart"></div>
{% endblock %}
和 base.html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="{{ url_for('static', filename='css/main.css') }}" type="text/css" rel="stylesheet">
{% block head %}{% endblock %}
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>
但它仍然不起作用。 - 我觉得jsonData转JS有问题。
【问题讨论】:
-
如果你想直接从json创建google的数据表 -->
new google.visualization.DataTable(jsonData)-- 以下是格式 --> Format of the Constructor's JavaScript Literal data Parameter -
谢谢! - 我怎样才能实现 json 数据格式来获得一个 googel 柱形图?
-
对不起,我对这个话题完全陌生,没有胶水,我必须在我的谷歌柱形图中实现 json 代码。
标签: python json flask google-visualization google-barchart