-1

My function calls Matplotlib to create and save a figure based on dates from user's input.

I save a new figure in my static folder like this:

plt.savefig('insights/static/chart.png')
return render_template("chart.html")

My template calls the figure like this:

<img src="/static/chart.png">

When the user enters new dates Matplotlib creates a new figure that overrides the existing figure file in static. The figure on the server is updated but the image displayed in my template is not. To update the new figure I need to save the template.

I think I have a problem with caching... Could anyone suggest a workaround?

aviss
  • 1,527
  • 4
  • 21
  • 40
  • use date and time in image name - and send this name to template. Or at least try `src="/static/chart.png?var=some_random_value"` and browser should treats this name as new file. – furas Dec 21 '16 at 00:38
  • 1
    Am I not missing some framework context? Templates, caching, static folder...what is the background? – Andras Deak Dec 21 '16 at 00:40
  • server treats `src="/static/chart.png?var=some_random_value"` as `src="/static/chart.png"` (and it changes nothing) but for browser it is different link (different file) which it has no in cache - so it has to download again. – furas Dec 21 '16 at 00:43
  • It worked but only for the first round... I guess I need to generate a random number inside my template. Can I do it without javascript? – aviss Dec 21 '16 at 01:01

1 Answers1

0

I think there are numerous solutions out for forcing the browser to refresh the image or the complete page content.

Is there a way to force browsers to refresh/download images?

Refresh image with a new one at the same url

What is the best way to force an image refresh on a webpage?

How to force a web browser NOT to cache images

PHP force refresh image

Some use JavaScript but others don't. The two main concepts are:

  1. Use a different filename every time or use a GET variable (?var=...)
  2. Set the HTML Meta tags to prevent caching.
Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 251,038
  • 37
  • 461
  • 518
  • Thank you very much. I figured out how to do it using some examples you mentioned. I decided to name my files using timestamp: – aviss Dec 21 '16 at 20:26
  • `timestr = time.strftime("%Y%m%d-%H%M%S") plt.savefig('insights/static/charts/'+timestr+'.png') return render_template("chart.html", timestr=timestr)` – aviss Dec 21 '16 at 20:30