Flask Web应用程序:Google饼图未显示在html输出中

时间:2019-01-21 11:51:59

标签: python flask google-visualization

我想通过Google饼图显示当前数据库的统计信息。但是,即使在检查元素时可以看到其相关的div元素,饼图也不会显示在html输出中。

这是html文件,数据来自与数据库链接的字典,我已经检查了该数据是否存在。

<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {

    var data = google.visualization.arrayToDataTable([

            ['Domain', 'Number of artist in our database'],
            {% for k,v in dic.items() %}
                 [{{k|safe}},  {{v|safe}}],
                 {% endfor %}
             ]);
    var options = {
                width: 400,
      height: 240,
      title: 'Distribution of domains in our database',
      colors: ['#41E0A9', '#00B973', '#00AA5A', '#00AA5A', '#00CD8C']
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
  }
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px; margin-left:400px;margin-top:20px;"></div>
</body>
</html>

Python flask函数

 @app.route('/recruiter', methods=['POST', 'GET'])
 def recruiter():
  if session.get("email"):
    curl = mysql.connection.cursor()
    curl.execute("SELECT * FROM projects")
    data = curl.fetchall()
    curl.close()
    username = session.get("username")
    curl = mysql.connection.cursor()
    domain_dict = {}
    select_stmt = ("SELECT domain ,COUNT(*) FROM freelancers GROUP BY domain")
    curl.execute(select_stmt)
    tuples=curl.fetchall()
    dic = {}
    for i in range(len(tuples)):
      k = list(tuples[i].values())[0]
      v = list(tuples[i].values())[1]
      dic[k]=v

    curl.close()
    return render_template(
        "recruiter_2.html",
        projects=data,
        dic=dic)
 else:
    return redirect(url_for('login'))

这是字典dic的输出:

{'Graphic Design': 2, 'Illustrator': 2, 
 'Animator': 2, 'Digital Designer': 2, 
 'Photographer': 2, 'Filmmaker': 2}

如果您能指出我在引用Jinja时犯了什么错误,这将对您有所帮助。当我为每个部分手动设置数字时,饼图也可以正常工作。 Jinja2循环错误吗?

感谢您的帮助^^

1 个答案:

答案 0 :(得分:0)

不使用for循环可解决此问题。而不是像这样初始化数据变量:

.0001
.222
.217

以这种方式初始化它:

     var data = google.visualization.arrayToDataTable([

       ['Domain', 'Number of artist in our database'],
         {% for k,v in dic.items() %}
              [{{k|safe}},  {{v|safe}}],
              {% endfor %}
          ]);