Chart.js无法从Flask python更新或接收数据

时间:2018-12-18 15:19:46

标签: javascript python flask chart.js

我正在尝试使用python脚本中的数据为网络应用创建交互式图表。

错误是来自python代码的数据未在chart.js脚本上传输或更新,并且不在html上输出。

这3个脚本的流程:来自python的标签和数据,进入chart.js以呈现条形图,并在html上输出

当我将非洲(数据点)从2447更改为5578时,图表不会更新。我不确定问题是从python转移还是呈现图表。

Python

from flask import Flask,render_template
app = Flask(__name__)

@app.route("/")
def result():
   labels = ["Africa", "Asia", "Europe", "Latin America", "North America"]

   data = [5578,5267,734,784,433]

   return render_template("result.html", labels=labels, data=data)
if __name__ == '__main__':
app.debug = True
app.run()

script1.js

new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
  labels: "{{labels}}",
  datasets: [
    {
      label: "Population (millions)",
      backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
      data: "{{data }}"
    }
  ]
},
options: {
  legend: { display: false },
  title: {
    display: true,
    text: 'Predicted world population (millions) in 2050'
  }
}
});

HTML

  <!DOCTYPE html>
<html>
  <head>
    <title>New</title>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"> 
</script>

  </head>
  <body>
  <h1>Test</h1>
    <div class="wrapper">
    <canvas id="bar-chart" width="800" height="450"></canvas>
    </div>

     <script src="{{ url_for('static', filename='script1.js') }}"></script>

   </body>
  </html>

5 个答案:

答案 0 :(得分:1)

script1.js不会由flask.render_template呈现,因为它只能由script标记链接。但是,与尝试将值本身呈现在模板中相比,将请求发送到后端以获取jsonified数据是一种更好的做法。在Python文件中创建一条附加路由,以根据ajax请求返回值:

import json
@app.route("/")
def result():
  return render_template("result.html")

@app.route('/get_data')
def get_data():
  labels = ["Africa", "Asia", "Europe", "Latin America", "North America"]
  data = [5578,5267,734,784,433]
  return flask.jsonify({'payload':json.dumps({'data':data, 'labels':labels})})

不要忘记在HTML中包含jquery以支持ajax调用:

<head> 
  <title>New</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"> 
</head>

最后,在script1.js中:

$(document).ready(function(){
   var _data;
   var _labels;
  $.ajax({
   url: "/get_data",
   type: "get",
   data: {vals: ''},
   success: function(response) {
     full_data = JSON.parse(response.payload);
     _data = full_data['data'];
     _labels = full_data['labels'];
   },

 });
 new Chart(document.getElementById("bar-chart"), {
  type: 'bar',
 data: {
   labels: _labels,
   datasets: [
   {
    label: "Population (millions)",
    backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
   data: _data
   }
   ]
   },
    options: {
    legend: { display: false },
     title: {
      display: true,
     text: 'Predicted world population (millions) in 2050'
   }
  }
 });
});

答案 1 :(得分:0)

要渲染javascript(替换变量),请将javascript放在要渲染的html文件中,并使用Flask jinja过滤器tojson:示例:

  <!DOCTYPE html>
  <html>
    <head>
      <title>New</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>

    </head>
    <body>
    <h1>Test</h1>
      <div class="wrapper">
      <canvas id="bar-chart" width="800" height="450"></canvas>
      </div>

      <!-- <script src="{{ url_for('static', filename='script1.js') }}"></script> -->
      <script>
          //console.log({{labels|tojson}});
          //console.log({{data|tojson}});
          new Chart(document.getElementById("bar-chart"), {
              type: 'bar',
              data: {
                labels: {{labels|tojson}},
                datasets: [
                  {
                    label: "Population (millions)",
                    backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
                    data: {{data|tojson}}
                  }
                ]
              },
              options: {
                legend: { display: false },
                title: {
                  display: true,
                  text: 'Predicted world population (millions) in 2050'
                }
              }
              });
      </script>

    </body>
    </html>

答案 2 :(得分:0)

响应@Lko注释以将js保存在单独文件中的代码示例,请参阅我对上一篇文章的注释。

文件结构: \ main.py \ static \ script1.js \ templates \ result.html

HTML:

    <!DOCTYPE html>
    <html>
      <head>
        <title>New</title>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>

      </head>
      <body>
      <h1>Test</h1>
        <div class="wrapper">
        <canvas id="bar-chart" width="800" height="450"></canvas>
        </div>

        <!-- <script src="{{ url_for('static', filename='script1.js') }}"></script> -->
        <script type = "text/javascript">
            var labelsVar={{labels|tojson}};
            var dataVar={{data|tojson}};
        </script>
        <script type = "text/javascript"  src="{{ url_for('static', filename = 'script1.js') }}"></script>
      </body>
      </html>

Javascript:

  console.log(labelsVar);
  console.log(dataVar);
  new Chart(document.getElementById("bar-chart"), {
      type: 'bar',
      data: {
        labels: labelsVar,
        datasets: [
          {
            label: "Population (millions)",
            backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
            data: dataVar
          }
        ]
      },
      options: {
        legend: { display: false },
        title: {
          display: true,
          text: 'Predicted world population (millions) in 2050'
        }
      }
      });

答案 3 :(得分:0)

data:JSON.parse('{{data}}')

我无法将烧瓶应用程序中的数据传递到html中的脚本部分,因此我做到了,并且奏效了。

答案 4 :(得分:0)

您可以将数据传递到列表上(使用render_template),并使用以下方法在html上检索:

labels: [{% for item in families %}
         "{{ item }}",
         {% endfor %}]