forget-cancellare-vecchi-toot/lib/cachebust.py

38 lines
1.2 KiB
Python
Raw Normal View History

2017-08-07 21:50:31 +02:00
from flask import url_for, abort
import os
2017-08-29 14:46:32 +02:00
2017-08-07 21:50:31 +02:00
def cachebust(app):
2017-08-29 21:27:38 +02:00
# pylint: disable=unused-variable
@app.route('/static-cb/<int:timestamp>/<path:filename>')
2017-08-07 21:50:31 +02:00
def static_cachebust(timestamp, filename):
path = os.path.join(app.static_folder, filename)
try:
mtime = os.stat(path).st_mtime
except Exception:
return abort(404)
2017-08-07 21:50:31 +02:00
if abs(mtime - timestamp) > 1:
abort(404)
else:
resp = app.view_functions['static'](filename=filename)
2017-08-29 14:46:32 +02:00
resp.headers.set(
'cache-control',
'public, immutable, max-age={}'.format(60*60*24*365))
2017-08-07 21:50:31 +02:00
if 'expires' in resp.headers:
resp.headers.remove('expires')
return resp
@app.context_processor
def replace_url_for():
2017-08-29 14:46:32 +02:00
return dict(url_for=cachebust_url_for)
2017-08-07 21:50:31 +02:00
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