From 017aa64c03881a011702e5e17612af77953e11e1 Mon Sep 17 00:00:00 2001 From: codl Date: Mon, 7 Aug 2017 21:50:31 +0200 Subject: [PATCH] add cachebusting for static files --- app.py | 4 +++- lib/__init__.py | 1 + lib/cachebust.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 lib/cachebust.py diff --git a/app.py b/app.py index 318af59..6f74d4b 100644 --- a/app.py +++ b/app.py @@ -3,6 +3,7 @@ from flask_sqlalchemy import SQLAlchemy from sqlalchemy import MetaData from flask_migrate import Migrate import version +from lib import cachebust app = Flask(__name__) @@ -36,9 +37,10 @@ if 'SENTRY_DSN' in app.config: app.config['SENTRY_CONFIG']['release'] = version.version sentry = Sentry(app, dsn=app.config['SENTRY_DSN']) +url_for = cachebust(app) + @app.context_processor def inject_static(): - from flask import url_for def static(filename, **kwargs): return url_for('static', filename=filename, **kwargs) return {'st': static} diff --git a/lib/__init__.py b/lib/__init__.py index 4b0da44..22e9bcf 100644 --- a/lib/__init__.py +++ b/lib/__init__.py @@ -1,3 +1,4 @@ from .auth import require_auth from .interval import decompose_interval from .interval import SCALES as interval_scales +from .cachebust import cachebust diff --git a/lib/cachebust.py b/lib/cachebust.py new file mode 100644 index 0000000..7edda78 --- /dev/null +++ b/lib/cachebust.py @@ -0,0 +1,28 @@ +from flask import url_for, abort +import os +def cachebust(app): + @app.route('/static-/') + def static_cachebust(timestamp, filename): + path = os.path.join(app.static_folder, filename) + mtime = os.stat(path).st_mtime + if abs(mtime - timestamp) > 1: + abort(404) + else: + resp = app.view_functions['static'](filename=filename) + resp.headers.set('cache-control', 'public, immutable, max-age=%s' % (60*60*24*365,)) + if 'expires' in resp.headers: + resp.headers.remove('expires') + return resp + + @app.context_processor + def replace_url_for(): + return dict(url_for = cachebust_url_for) + + def cachebust_url_for(endpoint, **kwargs): + if endpoint == 'static': + endpoint = 'static_cachebust' + path = os.path.join(app.static_folder, kwargs.get('filename')) + kwargs['timestamp'] = int(os.stat(path).st_mtime) + return url_for(endpoint, **kwargs) + + return cachebust_url_for