Skip to content

Instantly share code, notes, and snippets.

@mfenniak
Created June 23, 2012 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfenniak/2978748 to your computer and use it in GitHub Desktop.
Save mfenniak/2978748 to your computer and use it in GitHub Desktop.
An extension of Flask that adds last-modified file time information to static file URLs built by url_for
import os.path
from flask import Flask
from flask.helpers import safe_join
# Injects an "mt" parameter on the URLs of static files that contains the
# last-modified time of the file. This allows the use of aggressive cache
# settings on static files, while ensuring that content changes are reflected
# immediately due to the new URLs. Note that if multiple servers have
# different mod times on files, this can cause static files to be reloaded more
# often than needed.
class AddStaticFileModTimeFlask(Flask):
def inject_url_defaults(self, endpoint, values):
super(AddStaticFileModTimeFlask, self).inject_url_defaults(endpoint, values)
if endpoint == "static" and "filename" in values:
filepath = safe_join(self.static_folder, values["filename"])
if os.path.isfile(filepath):
values["mt"] = os.path.getmtime(filepath)
app = AddStaticFileModTimeFlask(__name__)
# ...
@mfenniak
Copy link
Author

I threw this together for a project that I was working on. It seems to work well, but then I realized that git does not maintain last-modified times on files and I was using git for deployments to multiple web servers. So I'm looking at alternative approaches, but I thought I'd throw this up on gist and maybe it'll be useful to someone, someday.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment