49 lines
1.2 KiB
Python
49 lines
1.2 KiB
Python
import os
|
|
import hashlib
|
|
from functools import lru_cache
|
|
from flask import current_app
|
|
|
|
@lru_cache(maxsize=128)
|
|
def get_file_hash(filepath):
|
|
"""
|
|
Get the MD5 hash of a file's contents.
|
|
Uses LRU cache to avoid re-reading files that haven't changed.
|
|
|
|
Args:
|
|
filepath: The path to the file
|
|
|
|
Returns:
|
|
str: The MD5 hash of the file contents
|
|
"""
|
|
try:
|
|
with open(filepath, 'rb') as f:
|
|
return hashlib.md5(f.read()).hexdigest()
|
|
except (IOError, OSError):
|
|
return None
|
|
|
|
def get_asset_version(filename):
|
|
"""
|
|
Get the version hash for a static asset.
|
|
|
|
Args:
|
|
filename: The filename of the static asset
|
|
|
|
Returns:
|
|
str: The version hash or None if file not found
|
|
"""
|
|
if not filename:
|
|
return None
|
|
|
|
# Get the absolute path to the static file
|
|
static_dir = os.path.join(current_app.root_path, 'static')
|
|
filepath = os.path.join(static_dir, filename)
|
|
|
|
# Get the file hash
|
|
file_hash = get_file_hash(filepath)
|
|
|
|
# If file not found or error reading, return None
|
|
if not file_hash:
|
|
return None
|
|
|
|
# Return first 8 characters of hash as version
|
|
return file_hash[:8] |