🔍 Code Extractor

function add_cache_headers

Maturity: 47

A Flask after_request decorator function that adds HTTP cache control headers to responses based on the application's debug mode, content type, and request endpoint.

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
439 - 455
Complexity:
simple

Purpose

This function manages HTTP caching behavior for a Flask web application. In debug mode, it disables all caching to ensure developers see fresh content. In production, it implements a tiered caching strategy: static files are cached for 5 minutes with public access, API endpoints have caching disabled, and other routes require revalidation. This ensures optimal performance while maintaining data freshness where needed.

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=300'
        elif request.path.startswith('/api/'):
            response.headers['Cache-Control'] = 'no-cache, no-store, 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 contains the HTTP response data including status code, headers, and body content. The function modifies the headers of this response object before returning it.

Return Value

Returns the same Flask Response object that was passed in, but with modified Cache-Control, Pragma, and Expires headers added based on the application's debug mode and the request context. The response object is of type flask.Response or flask.wrappers.Response.

Dependencies

  • flask

Required Imports

from flask import request

Usage Example

from flask import Flask, request, make_response

app = Flask(__name__)
DEBUG_MODE = False  # Set based on environment

@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=300'
        elif request.path.startswith('/api/'):
            response.headers['Cache-Control'] = 'no-cache, no-store, 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': 'value'}

if __name__ == '__main__':
    app.run()

Best Practices

  • Ensure DEBUG_MODE is properly set based on your deployment environment (True for development, False for production)
  • This function should be registered as an after_request handler using @app.after_request decorator
  • The function relies on Flask's request context, so it only works within active request handling
  • Static file caching is set to 5 minutes (max-age=300); adjust this value based on your deployment frequency
  • API endpoints have caching completely disabled to ensure fresh data; consider if this is appropriate for your use case
  • The function checks request.endpoint and request.path, ensure your Flask routes are properly configured
  • Consider adding ETag or Last-Modified headers for more sophisticated caching strategies
  • Be aware that 'Pragma: no-cache' is for HTTP/1.0 compatibility and may not be necessary for modern applications

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function add_cache_headers_v1 96.4% similar

    Flask after_request decorator function that adds HTTP cache control headers to responses based on debug mode, endpoint type, and request path.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function debug_cache_info 63.1% similar

    Flask debug endpoint that provides comprehensive cache busting information including static file versions, modification times, and cache buster values.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function inject_cache_buster 59.6% similar

    Flask context processor that injects cache busting variables into all Jinja2 templates to prevent browser caching of static assets.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function require_auth 50.5% similar

    A decorator function that enforces authentication requirements on Flask route handlers by checking if a user is authenticated before allowing access to the decorated function.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function require_auth_v1 50.5% similar

    A Flask decorator that enforces authentication by checking if a user is authenticated before allowing access to a protected route, redirecting to login if not authenticated.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
← Back to Browse