Created
April 3, 2011 18:16
-
-
Save gearheart/900633 to your computer and use it in GitHub Desktop.
Python library to insert images hash to urls in css file. Makes browser reload images on change.
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
| #!/usr/bin/python | |
| import os.path | |
| import re | |
| import hashlib | |
| def file_hash(filename, block_size=2**20): | |
| md5 = hashlib.md5() | |
| with open(filename, 'rb') as f: | |
| for data in iter(lambda: f.read(block_size), ''): | |
| md5.update(data) | |
| return md5.hexdigest() | |
| def find_replace(match, basedir): | |
| match = match.replace("'", '') | |
| if '?' in match or '#' in match or match.startswith('http://'): | |
| print 'skipping: ', match | |
| return None | |
| filename = os.path.join(basedir, match) | |
| return '%s?%s' % (match, file_hash(filename)[:10]) | |
| def insert_hash(filename, debug=False): | |
| basedir = os.path.dirname(filename) | |
| css = open(filename).read() | |
| matches = re.findall(r"url\((.*?)\)", css) | |
| replacements = dict([ | |
| (match, find_replace(match, basedir)) | |
| for match in matches | |
| ]) | |
| if debug: | |
| for key, value in replacements.iteritems(): | |
| print key, ' => ', value | |
| else: | |
| for match, repl in replacements.iteritems(): | |
| if repl: | |
| css = css.replace(match, repl) | |
| out = open(filename, 'w') | |
| out.write(css) | |
| out.close() | |
| if __name__ == '__main__': | |
| from optparse import OptionParser | |
| usage = 'usage: %prog filename.css' | |
| parser = OptionParser(usage=usage) | |
| parser.add_option("", "--debug", action="store_true", dest="debug", default=False, | |
| help="When set, just output list of substitutions.") | |
| (options, args) = parser.parse_args() | |
| if len(args) < 1: | |
| print 'You must provide file name.' | |
| insert_hash(os.path.realpath(args[0]), options.debug) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment