Created
June 23, 2012 15:49
-
-
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
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
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__) | |
# ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.