Forked from iximiuz/flask_static_files_cache_invalidator.py
Last active
August 30, 2015 07:03
-
-
Save vayn/391cb9aac2b9ac830969 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 hidden or 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... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment