Last active
August 29, 2015 14:07
-
-
Save nealnote/c5547a1af12271cd17be to your computer and use it in GitHub Desktop.
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
#!/usr/bin/python | |
# -*- encoding: utf-8 -*- | |
import os | |
import hashlib | |
import logging | |
_hashes = {} | |
def get_absolute_path(root, path): | |
"""Returns the absolute path | |
""" | |
abspath = os.path.abspath(os.path.join(root, path)) | |
return abspath | |
def get_content(abspath, start=None, end=None): | |
"""Retunrs the content of given absolute path | |
""" | |
with open(abspath, "rb") as file: | |
if start is not None: | |
file.seek(start) | |
if end is not None: | |
remaining = end - ( start or 0) | |
else: | |
remaining = None | |
while True: | |
chunk_size = 64 * 1024 | |
if remaining is not None and remaining < chunk_size: | |
chunk_size = remaining | |
chunk = file.read(chunk_size) | |
if chunk: | |
if remaining is not None: | |
remaining -= len(chunk) | |
yield chunk | |
else: | |
if remaining is not None: | |
assert remaining == 0 | |
return | |
def get_content_version(abspath): | |
"""Returns a version string for the resource at the given path | |
""" | |
data = get_content(abspath) | |
hasher = hashlib.md5() | |
if isinstance(data, bytes): | |
hasher.update(data) | |
else: | |
for chunk in data: | |
hasher.update(chunk) | |
return hasher.hexdigest() | |
def get_version(abs_path): | |
"""Generate the version string to be used in static URLs | |
""" | |
hashes = _hashes | |
if abs_path not in hashes: | |
try: | |
hashes[abs_path] = get_content_version(abs_path) | |
except Exception: | |
logging.error("Could not open file %r", abs_path) | |
hashes[abs_path] = None | |
hsh = hashes.get(abs_path) | |
if hsh: | |
return hsh | |
return None | |
def init(): | |
root = os.path.dirname(__file__) | |
path = 'example/underscore.js' | |
abs_path = get_absolute_path(root, path) | |
print(get_version(abs_path)) | |
if __name__ == '__main__': | |
init() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment