
Provides a module `assetcache` to support automatic cachebusting of static web assets, rather than the current approach of incrementing a version number. On module load, it walks the file/assets/ dir, computes a CRC32 of each asset, and provides those hashes via `assetcache_get(path)` at runtime. The primary consumer of hashes at present is the new `asset` filter for Jinja2, which accepts a relative asset path and returns the full path, with cache busting, suitable for final use in the template. Ex: `{{ 'css/main.css' | asset }}`
20 lines
504 B
Python
20 lines
504 B
Python
import os
|
|
import zlib
|
|
from collections import defaultdict
|
|
|
|
ASSET_DIR = 'files/assets'
|
|
ASSET_CACHE = defaultdict(lambda: None)
|
|
|
|
def assetcache_build(asset_dir):
|
|
for root, dirs, files in os.walk(asset_dir):
|
|
for fname in files:
|
|
fpath = root + '/' + fname
|
|
relpath = fpath[len(asset_dir) + 1:].replace('\\', '/')
|
|
with open(fpath, 'rb') as f:
|
|
fhash = zlib.crc32(f.read())
|
|
ASSET_CACHE[relpath] = '%x' % fhash
|
|
|
|
def assetcache_get(path):
|
|
return ASSET_CACHE[path]
|
|
|
|
assetcache_build(ASSET_DIR)
|