尝试在带有Flask和phyton的html上显示图像,该图像会更改每次刷新

我正在为大学设计一个项目,该项目从Twitter获取数据并创建一些图形,然后使用flask在html上显示这些图形。这些图形是使用matplot创建的,然后将它们保存为.png图像。每次用户刷新网页时,数据也会更新其架子,因此将再次生成图形。我的问题是,显示图像的唯一方法是通过创建静态文件夹,而当本地文件夹创建时,这种方法不会更新图像。我想知道刷新页面后如何更改图像。

这是我的烧瓶应用程序

app = flask(__name__)

labels = ["Postive","Negative","Neutral"]
colors = ["#00ff7f","#d80000","#00008B"]


@app.route("/pie")
def chart():
    negative,positive,neutral = get_data("China")
    values = [positive,negative,neutral]
    pie_labels = labels
    pie_values = values
    return render_template('pie_chart.html',image="static/images/locations.png",title='Positive and Negative',max=1700,set=zip(values,labels,colors))

if __name__ == "__main__":
    app.run()

这是HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>{{ title }}</title>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'></script>
</head>

<body>
    <h1>{{ title }}</h1>

    <canvas id="chart" 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("chart").getcontext("2d");
      steps = 10
      max = {{ max }}
      // draw pie chart
      new Chart(document.getElementById("chart").getcontext("2d")).Pie(pieData);
    </script>
    <img src="{{ image }}">
</body>
</html>

正如我所说,这里的事情将是如何在网页中显示图像并在每次数据更新(刷新)时对其进行更新。

sdqzangel 回答:尝试在带有Flask和phyton的html上显示图像,该图像会更改每次刷新

您需要另一条路线,该路线将使用Flask send_file方法返回动态图像。然后,您可以使用现有路由返回的HTML链接到该路由。

示例:

@app.route("/images/pie")
def chart_image():
    # Get data,but only make chart image
    image_object = some_thing_to_make_image_data_for_a_country()
    return flask.send_file(image_object,mimetype="image/png")

@app.route("/pie")
def chart_data():
    # Get data,but only get values
    negative,positive,neutral = get_data(country)
    values = [positive,negative,neutral]
    pie_labels = labels
    pie_values = values
    return render_template('pie_chart.html',image="images/pie",title='Positive and Negative',max=1700,set=zip(values,labels,colors))

这将提取两次数据,除非您在一条路由中将数据缓存在app中,而在另一条路由中使用缓存的数据。

本文链接:https://www.f2er.com/3150071.html

大家都在问