Skip to content

Instantly share code, notes, and snippets.

@wolfgangmeyers
Created February 1, 2016 00:07
Show Gist options
  • Save wolfgangmeyers/9a6883887b68ace5e83a to your computer and use it in GitHub Desktop.
Save wolfgangmeyers/9a6883887b68ace5e83a to your computer and use it in GitHub Desktop.
Simple python script to add a query string to all css / js files using a unix timestamp to force refresh of static assets.
#!/usr/bin/env python
import time
def cachebust_script_src(line):
src_i = line.find("src=")
begin_src = src_i + 5
end_src = line.find("\"", begin_src)
src_contents = line[begin_src:end_src]
parts = src_contents.split("?")
base_src = parts[0]
src_contents = base_src + "?" + str(int(time.time() * 1000))
before_src = line[:src_i]
after_src = line[end_src:]
line = before_src + "src=\"" + src_contents + after_src
return line
def cachebust_css_href(line):
href_i = line.find("href=")
begin_href = href_i + 6
end_href = line.find("\"", begin_href)
href_contents = line[begin_href:end_href]
parts = href_contents.split("?")
base_href = parts[0]
href_contents = base_href + "?" + str(int(time.time() * 1000))
before_href = line[:href_i]
after_href = line[end_href:]
line = before_href + "href=\"" + href_contents + after_href
return line
def update_template_file(name):
print "Updating template file:", name
lines = []
with open(name) as f:
for line in f:
if "<script" in line:
line = cachebust_script_src(line)
elif "rel=\"stylesheet\"" in line:
line = cachebust_css_href(line)
lines.append(line)
with open(name, "w") as f:
for line in lines:
f.write(line)
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
config_file = sys.argv[1]
else:
config_file = "cachebuster-conf.txt"
with open(config_file) as f:
for line in f:
line = line.strip()
update_template_file(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment