【问题标题】:How to get multiple elements on a page using flask (tables, pie charts, etc.)如何使用烧瓶(表格、饼图等)在页面上获取多个元素
【发布时间】:2020-08-19 13:24:46
【问题描述】:

我正在尝试使用烧瓶将多个元素添加到单个页面。我可以使用下面的代码在很大程度上做到这一点,但无法获得多个图表。我将 python 与 chart.js 以及 pandas 一起用于数据。我也在使用 html 和 CSS。

Python:

d1 = {'Fruits' : pd.Series([10]),
     'Vegetables' : pd.Series([12]),
     'Drinks' : pd.Series([2])}
df1 = pd.DataFrame(d1)

d2 = {'Fruits' : pd.Series([1]),
     'Vegetables' : pd.Series([18]),
     'Drinks' : pd.Series([21])}
df2 = pd.DataFrame(d2)


labels_1 = [
    'Bananas', 'Apples',
    'Oranges', 'Strawberries', 'Lemons',
    'Watermelons', 'Coconuts'
]

values_1 = [
    10.0, 20.0, 10.0, 20.0, 20.0, 10.0, 10.0
]

labels_2 = [
    'Bananas', 'Apples',
    'Oranges', 'Strawberries', 'Lemons',
    'Watermelons', 'Coconuts'
]

values_2 = [
    20.0, 10.0, 20.0, 10.0, 10.0, 20.0, 10.0
]

labels_3 = [
    'Bananas', 'Apples',
    'Oranges', 'Strawberries', 'Lemons',
    'Watermelons', 'Coconuts'
]

values_3 = [
    30.0, 10.0, 10.0, 10.0, 20.0, 10.0, 10.0
]

colors = [
    "#46BFBD", "#F7464A", "#FDB45C", "#FEDCBA",
    "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
    "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]


app = Flask(__name__)
                  

@app.route('/dashboard')
def dashboard():
    return render_template('dashboard.html', title1='Day 1', tables1=[
                                df1.to_html(index=False, classes='dashboard1', header="true")], title2='Day 2', tables2=[
                                df2.to_html(index=False, classes='dashboard2', header="true")],
                                title3='Produce Sold on Monday', max=17000, set=zip(values_1, labels_1, values_2, labels_2, values_3, labels_3, colors),
                                title4='Produce Sold on Tuesday', title5='Produce Sold on Wednesday')


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Produce Records</title>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'></script>
</head>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style17.css') }}">
<body>
  <center>
    <h1>Fruit Stand Sales</h1>
  </center>
   <center>
    <h2>{{ title1 }}</h2>
  </center>
  <center>
{% for table in tables1 %}
            {{ table|safe }}
{% endfor %}
  </center>
  <center>
    <h2>{{ title2 }}</h2>
  </center>
   <center>
{% for table in tables2 %}
            {{ table|safe }}
{% endfor %}
  </center>
  <center>
    <h1>Produce Solde Breakdown</h1>
  </center>
  <center>
    <h2>{{ title3 }}</h2>
    <canvas id="chart1" width="600" height="400"></canvas>
    <script>
      var pieData = [
        {% for item, label, colors in set %}
          {
            value: {{item}},
            label: "{{label}}",
            color : "{{colors}}"
          },
        {% endfor %}
      ];

      // get bar chart canvas
      var mychart = document.getElementById("chart1").getContext("2d");
      steps = 10
      max = {{ max }}

      // draw pie chart
      new Chart(document.getElementById("chart1").getContext("2d")).Pie(pieData);
    </script>
    <h2>{{ title4 }}</h2>
    <canvas id="chart2" width="600" height="400"></canvas>
    <script>
      var pieData = [
        {% for item, label, colors in set %}
          {
            value: {{item}},
            label: "{{label}}",
            color : "{{colors}}"
          },
        {% endfor %}
      ];

      // get bar chart canvas
      var mychart = document.getElementById("chart2").getContext("2d");
      steps = 10
      max = {{ max }}

      // draw pie chart
      new Chart(document.getElementById("chart2").getContext("2d")).Pie(pieData);
    </script>
    <h2>{{ title5 }}</h2>
    <canvas id="chart3" width="600" height="400"></canvas>
    <script>
      var pieData = [
        {% for item, label, colors in set %}
          {
            value: {{item}},
            label: "{{label}}",
            color : "{{colors}}"
          },
        {% endfor %}
      ];

      // get bar chart canvas
      var mychart = document.getElementById("chart3").getContext("2d");
      steps = 10
      max = {{ max }}

      // draw pie chart
      new Chart(document.getElementById("chart3").getContext("2d")).Pie(pieData);
    </script>
  </center>
</body>
</html>

我收到的错误:

{% for item, label, colors in set %} ValueError:要解压的值太多(预计 3 个)

看起来我必须更改 HTML 以容纳多个图表,但我不知道该怎么做。这是最好的方法吗?我应该使用 matplotlib 之类的不同方法吗?

【问题讨论】:

    标签: python html pandas flask chart.js


    【解决方案1】:

    该错误是因为您的 zip 对象有 7 个要解压的值,而不是 3 个。 如果你做了{% for a, b, c, d, e, f, g in set %},它应该可以工作。

    您也可以像字典列表一样排列数据,例如:

    [{"item": ..., "label": ..., "color": ..., "value": ...}, ...]
    

    这样,您可以像这样渲染它们(不用担心如果您有更多的键并且您不想全部渲染它们):

    {% for i in set %}
      {
         value: "{{ i["item"] }}",
         label: "{{ i["label"] }}",
         color: "{{ i["color"] }}"
      },
    {% endfor %}
    

    【讨论】:

      【解决方案2】:

      我能够通过为每个图形设置 3 个不同的变量来实现这一点,因为“设置”是一个关键参数并且无法复制。这是我使用的代码:

      Python:

      @app.route('/dashboard')
      def dashboard():
          return render_template('dashboard.html', title1='Day 1', tables1=[
                                      df1.to_html(index=False, classes='dashboard1', header="true")], title2='Day 2', tables2=[
                                      df2.to_html(index=False, classes='dashboard2', header="true")],
                                      title3='Produce Sold on Monday', max=17000, set1=zip(values_1, labels_1, colors),
                                      title4='Produce Sold on Tuesday', set2=zip(values_2, labels_2, colors),
                                      title5='Produce Sold on Wednesday', set3=zip(values_3, labels_3, colors))
      
      
      if __name__ == '__main__':
          app.run(host='0.0.0.0', port=8080)
      

      HTML:

        <center>
          <h1>Produce Solde Breakdown</h1>
        </center>
        <center>
          <h2>{{ title3 }}</h2>
          <canvas id="chart1" width="600" height="400"></canvas>
          <script>
            var pieData = [
              {% for item, label, colors in set1 %}
                {
                  value: {{item}},
                  label: "{{label}}",
                  color : "{{colors}}"
                },
              {% endfor %}
            ];
      
            // get bar chart canvas
            var mychart = document.getElementById("chart1").getContext("2d");
            steps = 10
            max = {{ max }}
      
            // draw pie chart
            new Chart(document.getElementById("chart1").getContext("2d")).Pie(pieData);
          </script>
          <h2>{{ title4 }}</h2>
          <canvas id="chart2" width="600" height="400"></canvas>
          <script>
            var pieData = [
              {% for item, label, colors in set2 %}
                {
                  value: {{item}},
                  label: "{{label}}",
                  color : "{{colors}}"
                },
              {% endfor %}
            ];
      
            // get bar chart canvas
            var mychart = document.getElementById("chart2").getContext("2d");
            steps = 10
            max = {{ max }}
      
            // draw pie chart
            new Chart(document.getElementById("chart2").getContext("2d")).Pie(pieData);
          </script>
          <h2>{{ title5 }}</h2>
          <canvas id="chart3" width="600" height="400"></canvas>
          <script>
            var pieData = [
              {% for item, label, colors in set3 %}
                {
                  value: {{item}},
                  label: "{{label}}",
                  color : "{{colors}}"
                },
              {% endfor %}
            ];
      
            // get bar chart canvas
            var mychart = document.getElementById("chart3").getContext("2d");
            steps = 10
            max = {{ max }}
      
            // draw pie chart
            new Chart(document.getElementById("chart3").getContext("2d")).Pie(pieData);
          </script>
      

      【讨论】:

        猜你喜欢
        • 2020-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多