Files
notifications-admin/app/asset_fingerprinter.py
T

51 lines
1.6 KiB
Python
Raw Permalink Normal View History

2018-02-20 11:22:17 +00:00
import hashlib
2016-02-10 15:47:00 +00:00
class AssetFingerprinter(object):
"""
Get a unique hash for an asset file, so that it doesn't stay cached
when it changes
2016-02-10 15:47:00 +00:00
Usage:
2016-02-10 15:47:00 +00:00
in the application
template_data.asset_fingerprinter = AssetFingerprinter()
2016-02-10 15:47:00 +00:00
where template data is how you pass variables to every template.
2016-02-10 15:47:00 +00:00
in template.html:
{{ asset_fingerprinter.get_url('stylesheets/application.css') }}
2016-02-10 15:47:00 +00:00
* 'app/static' is assumed to be the root for all asset files
2016-02-10 15:47:00 +00:00
"""
def __init__(self, asset_root="/static/", filesystem_path="app/static/"):
2016-02-10 15:47:00 +00:00
self._cache = {}
self._asset_root = asset_root
self._filesystem_path = filesystem_path
2020-12-29 13:38:27 +00:00
def get_url(self, asset_path, with_querystring_hash=True):
if not with_querystring_hash:
return self._asset_root + asset_path
2016-02-10 15:47:00 +00:00
if asset_path not in self._cache:
self._cache[asset_path] = (
self._asset_root
+ asset_path
+ "?"
+ self.get_asset_fingerprint(self._filesystem_path + asset_path)
2016-02-10 15:47:00 +00:00
)
return self._cache[asset_path]
def get_asset_fingerprint(self, asset_file_path):
2022-08-26 16:04:30 +00:00
return hashlib.md5( # nosec B324 - hash value is not verified, so md5 is fine
2018-11-29 14:28:29 +00:00
self.get_asset_file_contents(asset_file_path)
2016-02-10 15:47:00 +00:00
).hexdigest()
def get_asset_file_contents(self, asset_file_path):
with open(asset_file_path, "rb") as asset_file:
2016-02-10 15:47:00 +00:00
contents = asset_file.read()
return contents
2018-10-26 15:39:32 +01:00
asset_fingerprinter = AssetFingerprinter()