Skip to content

Instantly share code, notes, and snippets.

@iximiuz
Last active October 28, 2019 18:56
Show Gist options
  • Save iximiuz/f16779933ceee3a9d181 to your computer and use it in GitHub Desktop.
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.
""" 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...
@1dot75cm
Copy link

1dot75cm commented Oct 4, 2016

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