🔍 Code Extractor

function touch_static_files

Maturity: 44

Updates the modification timestamp of CSS and JavaScript files in a static directory to force browser cache refresh.

File:
/tf/active/vicechatdev/vice_ai/dev_tools.py
Lines:
38 - 57
Complexity:
simple

Purpose

This utility function is designed to solve browser caching issues during development or deployment. It recursively searches for all .css and .js files in a 'static' directory (located relative to the script file) and updates their modification timestamps using the touch operation. This forces browsers and CDNs to recognize the files as changed and reload them, bypassing cached versions. Useful for ensuring users see the latest static assets after updates.

Source Code

def touch_static_files():
    """Touch static files to force cache refresh"""
    static_dir = Path(__file__).parent / "static"
    if not static_dir.exists():
        print("❌ Static directory not found")
        return
    
    touched_files = []
    for file_path in static_dir.rglob("*"):
        if file_path.is_file() and file_path.suffix in ['.css', '.js']:
            file_path.touch()
            touched_files.append(file_path.relative_to(static_dir))
    
    if touched_files:
        print(f"✅ Touched {len(touched_files)} static files to force cache refresh:")
        for file in touched_files:
            print(f"   📄 {file}")
    else:
        print("â„šī¸  No static files found to touch")
    print()

Return Value

This function does not return any value (implicitly returns None). It performs side effects by modifying file timestamps and printing status messages to stdout.

Required Imports

from pathlib import Path

Usage Example

from pathlib import Path

# Assuming this function is in a file called utils.py
# and there's a 'static' directory in the same location
# with structure like: static/css/style.css, static/js/app.js

def touch_static_files():
    """Touch static files to force cache refresh"""
    static_dir = Path(__file__).parent / "static"
    if not static_dir.exists():
        print("❌ Static directory not found")
        return
    
    touched_files = []
    for file_path in static_dir.rglob("*"):
        if file_path.is_file() and file_path.suffix in ['.css', '.js']:
            file_path.touch()
            touched_files.append(file_path.relative_to(static_dir))
    
    if touched_files:
        print(f"✅ Touched {len(touched_files)} static files to force cache refresh:")
        for file in touched_files:
            print(f"   📄 {file}")
    else:
        print("â„šī¸  No static files found to touch")
    print()

# Call the function to update timestamps
touch_static_files()

# Output example:
# ✅ Touched 3 static files to force cache refresh:
#    📄 css/style.css
#    📄 js/app.js
#    📄 js/utils.js

Best Practices

  • This function should be run during deployment or build processes to ensure cache invalidation
  • Ensure the script has write permissions to the static directory before calling this function
  • The function uses Path(__file__).parent which means it must be defined in a file (not in interactive Python shell)
  • Consider running this function as part of a pre-deployment script or CI/CD pipeline
  • The function only touches .css and .js files; modify the suffix list if other file types need cache busting
  • Be aware that touching files changes their modification time, which may affect version control systems or backup tools
  • For production environments, consider using versioned filenames or query parameters as alternative cache-busting strategies

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function check_static_files 73.8% similar

    Scans a 'static' directory for CSS and JavaScript files and prints their modification times relative to the current time.

    From: /tf/active/vicechatdev/vice_ai/dev_tools.py
  • function get_file_version 61.7% similar

    Generates a version string for static files to enable cache busting, using current time in debug mode or file modification time in production.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function get_file_version_v1 61.3% similar

    Generates a version string for static files based on their modification time, used for cache busting in web applications.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function file_cleanup 59.9% similar

    Removes files older than 60 seconds from the './static/files/' directory.

    From: /tf/active/vicechatdev/datacapture_integrated.py
  • function get_cache_buster 57.9% similar

    Returns a cache-busting string that varies based on the application mode: current timestamp in debug mode or a static version string in production mode.

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