Last active
October 28, 2019 18:56
-
-
Save iximiuz/f16779933ceee3a9d181 to your computer and use it in GitHub Desktop.
Flask: add static file's cache invalidator param to URLs generated by url_for(). Blueprints aware.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Inspired by http://flask.pocoo.org/snippets/40/ """ | |
app = Flask(__name__) | |
@app.url_defaults | |
def hashed_url_for_static_file(endpoint, values): | |
if 'static' == endpoint or endpoint.endswith('.static'): | |
filename = values.get('filename') | |
if filename: | |
if '.' in endpoint: # has higher priority | |
blueprint = endpoint.rsplit('.', 1)[0] | |
else: | |
blueprint = request.blueprint # can be None too | |
if blueprint: | |
static_folder = app.blueprints[blueprint].static_folder | |
else: | |
static_folder = app.static_folder | |
param_name = 'h' | |
while param_name in values: | |
param_name = '_' + param_name | |
values[param_name] = static_file_hash(os.path.join(static_folder, filename)) | |
def static_file_hash(filename): | |
return int(os.stat(filename).st_mtime) # or app.config['last_build_timestamp'] or md5(filename) or etc... |
Very useful, I just a little change. @Ostrovski
@app.url_defaults
def hashed_static_file(endpoint, values):
if 'static' == endpoint or endpoint.endswith('.static')
filename = values.get('filename')
if filename:
blueprint = request.blueprint
if '.' in endpoint: # blueprint
blueprint = endpoint.rsplit('.', 1)[0]
static_folder = app.static_folder
# use blueprint, but dont set `static_folder` option
if blueprint and app.blueprints[blueprint].static_folder:
static_folder = app.blueprints[blueprint].static_folder
fp = os.path.join(static_folder, filename)
if os.path.exists(fp):
values['_'] = int(os.stat(fp).st_mtime)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sorry, would you clarify your question?