function inject_cache_buster
Flask context processor that injects cache busting variables into all Jinja2 templates to prevent browser caching of static assets.
/tf/active/vicechatdev/vice_ai/complex_app.py
429 - 435
simple
Purpose
This function is a Flask context processor that automatically makes cache busting utilities available to all templates. It provides a cache buster string, a file version function, and debug mode flag to help manage browser caching of static files (CSS, JS, images). This ensures users always receive the latest version of static assets after deployments or updates.
Source Code
def inject_cache_buster():
"""Inject cache busting variables into all templates"""
return {
'cache_buster': get_cache_buster(),
'get_file_version': get_file_version,
'debug_mode': DEBUG_MODE
}
Return Value
Returns a dictionary with three keys: 'cache_buster' (a string/timestamp for cache invalidation), 'get_file_version' (a function to get file-specific versions), and 'debug_mode' (a boolean indicating if debug mode is enabled). This dictionary is automatically merged into the template context for all rendered templates.
Dependencies
flask
Required Imports
from flask import Flask
Usage Example
# Define required dependencies
from flask import Flask
import time
app = Flask(__name__)
DEBUG_MODE = True
def get_cache_buster():
return str(int(time.time()))
def get_file_version(filename):
return f"{filename}?v={get_cache_buster()}"
# Register the context processor
@app.context_processor
def inject_cache_buster():
return {
'cache_buster': get_cache_buster(),
'get_file_version': get_file_version,
'debug_mode': DEBUG_MODE
}
# In templates, use like:
# <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}?v={{ cache_buster }}">
# <script src="{{ get_file_version('app.js') }}"></script>
Best Practices
- Ensure get_cache_buster() returns a unique value that changes with each deployment (timestamp, git hash, or version number)
- The get_file_version function should be callable from templates and accept a filename parameter
- DEBUG_MODE should be set based on environment (development vs production)
- This decorator must be applied to the function for it to work as a context processor
- The returned dictionary keys become available as variables in all Jinja2 templates automatically
- Consider using a more stable cache buster in production (like git commit hash) rather than timestamp to avoid unnecessary cache invalidation
- Test that the cache buster values are properly injected into templates before deploying
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function inject_template_vars 79.7% similar
-
function debug_cache_info 69.8% similar
-
function get_cache_buster 66.1% similar
-
function add_cache_headers 59.6% similar
-
function add_cache_headers_v1 57.6% similar