Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purge client browser cache after deploying app to Heroku

My Flask application is hosted by Heroku and served on Nginx and uses Cloudflare as a CDN. There are times when I change static assets (images, CSS, JS, etc.) on the backend that get changed through deployment on Heroku. These changes will not change on the client's browser unless they manually purge their cache. The cache does expire on the client's browser every month as recommended, but I want the backend to manually tell client browsers to purge their cache for my website every time I deploy to Heroku and they load/reload my website after the fact. Is there a way to automize this process?

like image 498
nenur Avatar asked Jul 06 '20 17:07

nenur


1 Answers

If you're using the same filenames it'll use a cached-copy so why not provide versioning on your static files using a filter? You don't have to change the filename at all. Although do read about the caveats in the link provided.

import os
from some_app import app


@app.template_filter('autoversion')
def autoversion_filter(filename):
  # determining fullpath might be project specific
  fullpath = os.path.join('some_app/', filename[1:])
  try:
      timestamp = str(os.path.getmtime(fullpath))
  except OSError:
      return filename
  newfilename = "{0}?v={1}".format(filename, timestamp)
  return newfilename

Via https://ana-balica.github.io/2014/02/01/autoversioning-static-assets-in-flask/

“Don’t include a query string in the URL for static resources.” It says that most proxies will not cache static files with query parameters. Consequently that will increase the bandwidth, since all the resources will be downloaded on each request.

“To enable proxy caching for these resources, remove query strings from references to static resources, and instead encode the parameters into the file names themselves.” But this implies a slightly different implementation :)

like image 99
Harben Avatar answered Sep 27 '22 19:09

Harben