add cachebusting for static files

This commit is contained in:
codl 2017-08-07 21:50:31 +02:00
parent 0ae1fe260b
commit 017aa64c03
No known key found for this signature in database
GPG Key ID: 6CD7C8891ED1233A
3 changed files with 32 additions and 1 deletions

4
app.py
View File

@ -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}

View File

@ -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

28
lib/cachebust.py Normal file
View File

@ -0,0 +1,28 @@
from flask import url_for, abort
import os
def cachebust(app):
@app.route('/static-<int:timestamp>/<path:filename>')
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