【问题标题】:Using Google Charts with Flask dynamically动态使用带有 Flask 的 Google Charts
【发布时间】: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


【解决方案1】:

我最近在尝试为我正在制作的网络应用程序创建图表时遇到了同样的问题,甚至考虑使用 chart.js,因为我怀疑它会更容易,但我找到了解决方案。您需要做的是将要绘制为字典的数据传入,然后使用 html 文件中的 jinja 格式循环遍历它。即

    from flask import Flask, render_template, request, jsonify, url_for
    import gviz_api


    @app.route('/')
    def test():
        return render_template('chart.html', data={"Name":"Salary", "Mike":10000, "Jim":800, "Alice":12500,"Bob":7000})

    if __name__ == '__main__':
        app.run(debug=True)

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.arrayToDataTable([
             {% for k, v in data.items() %}
                {% if v is string %}
                  ['{{ k }}', '{{ v }}'],
                {% else %}
                  ['{{ k }}', {{ v }}],
                {% endif %}
             {% endfor %}
          ]);


          // 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 文件进行任何更改。这对我有用,所以我认为它也应该对你有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多