function add_cache_headers_v1
Flask after_request decorator function that adds HTTP cache control headers to responses based on debug mode, endpoint type, and request path.
/tf/active/vicechatdev/vice_ai/app.py
227 - 243
simple
Purpose
This function is designed to be used as a Flask after_request handler to manage caching behavior across different environments and endpoint types. In debug mode, it disables all caching to ensure developers see fresh content. In production, it enables caching for static files (1 hour) while preventing caching for API endpoints and dynamic content. This ensures optimal performance in production while maintaining development flexibility.
Source Code
def add_cache_headers(response):
"""Add appropriate cache headers based on content type and debug mode"""
if DEBUG_MODE:
# In debug mode, disable all caching
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
else:
# In production, allow caching for static files but with validation
if request.endpoint == 'static':
response.headers['Cache-Control'] = 'public, max-age=3600' # 1 hour cache
elif request.path.startswith('/api/'):
response.headers['Cache-Control'] = 'no-cache, must-revalidate'
else:
response.headers['Cache-Control'] = 'no-cache, must-revalidate'
return response
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
response |
- | - | positional_or_keyword |
Parameter Details
response: A Flask Response object that will be returned to the client. This object is automatically passed by Flask's after_request decorator mechanism and contains the HTTP response including status code, headers, and body content. The function modifies this object's headers before returning it.
Return Value
Returns the same Flask Response object that was passed in, but with modified Cache-Control, Pragma, and Expires headers. The specific headers added depend on the DEBUG_MODE setting and the request endpoint/path. The response object maintains all its original properties (status code, body, other headers) with only cache-related headers modified.
Dependencies
flask
Required Imports
from flask import Flask
from flask import request
Usage Example
from flask import Flask, request, make_response
app = Flask(__name__)
DEBUG_MODE = False # or True for development
@app.after_request
def add_cache_headers(response):
"""Add appropriate cache headers based on content type and debug mode"""
if DEBUG_MODE:
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
else:
if request.endpoint == 'static':
response.headers['Cache-Control'] = 'public, max-age=3600'
elif request.path.startswith('/api/'):
response.headers['Cache-Control'] = 'no-cache, must-revalidate'
else:
response.headers['Cache-Control'] = 'no-cache, must-revalidate'
return response
@app.route('/')
def index():
return 'Hello World'
@app.route('/api/data')
def api_data():
return {'data': 'example'}
if __name__ == '__main__':
app.run()
Best Practices
- Ensure DEBUG_MODE is properly set based on environment (True for development, False for production)
- This function should be registered using @app.after_request decorator to execute after every request
- The function must always return the response object to maintain Flask's request-response cycle
- Consider adjusting max-age value (currently 3600 seconds/1 hour) for static files based on deployment frequency
- Be aware that this function runs for every request, so keep logic lightweight
- Test caching behavior in both debug and production modes to ensure expected behavior
- Consider adding more granular caching rules for different static file types (CSS, JS, images) if needed
- Ensure the function is registered after the Flask app is initialized but before the app starts running
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function add_cache_headers 96.4% similar
-
function debug_cache_info 61.1% similar
-
function inject_cache_buster 57.6% similar
-
function check_debug_endpoint 50.4% similar
-
function get_cache_buster 48.4% similar