烧瓶未刷新图/图像未从烧瓶更新

时间:2020-10-06 04:14:14

标签: python-3.x matplotlib flask line-plot

下面是我们可以将其另存为runflasktest.py

的代码
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from flask import Flask, send_file, make_response, render_template, send_from_directory
#from flask_ngrok import run_with_ngrok
matplotlib.use('Agg')
import io

app = Flask(__name__)
#run_with_ngrok(app) 

#cache_config = Cache(app, config={'CACHE_TYPE': 'null'})
app.config["CACHE_TYPE"] = "null"

@app.route("/")
def home():
  dates = ['2010-11', '2011-12', '2012-13', '2013-14', '2014-15', '2015-16', '2016-17']
  steps = [9000, 9500.756, 9800.859, 10000.262, 9800.972, 10500.058, 11300.703]
  df= pd.DataFrame(
      {'date': dates, 'steps': steps})
  fig, axes = plt.subplots(nrows=1, ncols=1)
  major_xtick=[2,3,4,5,6,7]
  major_xticklabel=['2010-11','2011-12','2012-13','2013-14','2014-15','2015-16','2016-17']
  color=['blue','green','blue']
  ax=df.plot(ax=axes,figsize=(10,8),linewidth=2,marker='o'
          ,title="x-y line plot" \
          ,xlim=(0,8),ylim=(2000,15000) \
          , color=color)
  ax.set_xticks(major_xtick)
  ax.set_xticklabels(major_xticklabel)
  ax.legend()
  #bytes_image = io.BytesIO()
  #plt.savefig(bytes_image, format='png')
  plt.savefig('D:\\AI\\flasktest\\testflask\\abc.png')
  #bytes_image.seek(0)
  #bytes_obj = bytes_image #do_plot()
    
  # return render_template('create_plot.html', pfile='abc')
  return render_template('display_plot.html', myfile='abc')
  # return "<h3>  {{ pfile }} is successfully created</h3>"
  #return send_file(bytes_obj,
  #                   attachment_filename='plot.png',
  #                   mimetype='image/png')

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

@app.route('/uploads/<path:filename>')
def dfile(filename):
    return send_from_directory('D:\\AI\\flasktest\\testflask', filename, as_attachment=True)

在相同位置创建模板目录,并将以下html模板放置在名为display_plot.html的文件中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h1>Plot</h1>
<img src="{{ url_for('dfile',filename=myfile+'.png') }}" alt="My image1"/>
</body>
</html>

现在从anaconda python命令提示符处运行代码

set FLASK_APP=runflasktest.py
flask run

现在通过网络浏览器打开http://127.0.0.1:5000/

您将在Web浏览器中看到线条图图像。发布后进行任何更改,我将线图的颜色从红色更改为蓝色。现在,如果再试一次,您仍然会看到红色,这是旧图。

我尝试将CACHE_TYPE设置为NULL并将SEND_FILE_MAX_AGE_DEFAULT设置为NULL,并根据某些帖子的建议添加以下代码段,但没有任何帮助。

# No caching at all for API endpoints.
@app.after_request
def add_header(response):
    # response.cache_control.no_store = True
    if 'Cache-Control' not in response.headers:
        response.headers['Cache-Control'] = 'no-store'
    return response

0 个答案:

没有答案