Flask not refreshing the plot/ image not getting updated from flask

354 views Asked by At

Below is the code we can save it as 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)

Create a template directory in the same location and place the below html template in a file named 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>

Now run the code from anaconda python command prompt

set FLASK_APP=runflasktest.py
flask run

Now open http://127.0.0.1:5000/ from web browser

You will see the line plot image on web browser. Post this make any change the plot I changed the to color of the line plot from red to blue. Now if you try again you will still see red, which is old plot.

I have tried with CACHE_TYPE set to NULL with SEND_FILE_MAX_AGE_DEFAULT set to and also adding below code piece as suggest in some post, but nothing has helped.

# 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

There are 0 answers