Skip to content

Instantly share code, notes, and snippets.

@mikeckennedy
Created September 10, 2025 16:34
Show Gist options
  • Save mikeckennedy/9043cdb494bd32ce801902e2f65488fa to your computer and use it in GitHub Desktop.
Save mikeckennedy/9043cdb494bd32ce801902e2f65488fa to your computer and use it in GitHub Desktop.
Utility to add cache busting query parameter to all static elements on a site.
import hashlib
import os
from typing import Optional
from pyramid.request import Request
from pyramid.response import Response
def build_cache_id(
filename: str,
dev_mode: bool,
file_hashes: dict,
folder_path: str,
log_hash_operations: bool
):
if not filename:
return 'ERROR_NO_FILE'
file_lw = filename.strip().lower()
if not dev_mode and file_lw in file_hashes:
return file_hashes[file_lw]
if log_hash_operations:
print('Building new hash for ' + file_lw)
fullname = os.path.abspath(os.path.join(folder_path, filename.lstrip('/')))
if not os.path.exists(fullname):
if log_hash_operations:
print('Failed to generate hash for MISSING file ' + fullname)
return 'ERROR_MISSING_FILE'
if os.path.isdir(fullname):
if log_hash_operations:
print('Failed to generate hash for MISSING file ' + fullname)
return 'ERROR_IS_DIRECTORY'
file_hashes[file_lw] = get_file_hash(fullname)
return file_hashes[file_lw]
def get_file_hash(filename: str) -> str:
md5 = hashlib.md5()
with open(filename, 'rb') as fin:
data = fin.read()
md5.update(data)
return md5.hexdigest()[-6:]
def cache_response(
request: Request,
is_dev_mode: bool,
seconds: int = 60,
in_browser_only: bool = True,
response: Optional[Response] = None,
):
if is_dev_mode:
return
vis = 'private' if in_browser_only else 'public'
request.response.headers['Cache-Control'] = f'{vis}, max-age={seconds}'
if response:
response.headers['Cache-Control'] = f'{vis}, max-age={seconds}'
@mikeckennedy
Copy link
Author

Example usage in Chameleon:

<link href='$/static/css/landing-page.css?cache_id=${view.build_cache_id("/static/css/landing-page.css")}' rel="stylesheet">

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment