🔍 Code Extractor

function get_file_version

Maturity: 49

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

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
406 - 422
Complexity:
simple

Purpose

This function provides cache-busting functionality for static assets (CSS, JS, images) in a Flask web application. In debug mode, it returns the current timestamp to force browser refresh on every request. In production, it uses the file's modification time to generate a stable version string that only changes when the file is updated. This ensures browsers cache static files appropriately while still loading updates when files change.

Source Code

def get_file_version(filename):
    """Get version string for static files based on modification time or current time in debug mode"""
    if DEBUG_MODE:
        # In debug mode, use current timestamp to force refresh every request
        return str(int(time.time()))
    
    try:
        # Try to get file modification time for production cache busting
        file_path = os.path.join(app.static_folder, filename)
        if os.path.exists(file_path):
            mtime = os.path.getmtime(file_path)
            return str(int(mtime))
    except (OSError, AttributeError):
        pass
    
    # Fallback to startup time
    return CACHE_BUST_VERSION

Parameters

Name Type Default Kind
filename - - positional_or_keyword

Parameter Details

filename: The relative path/name of the static file (e.g., 'css/style.css', 'js/app.js') within the Flask application's static folder. This is used to locate the file and retrieve its modification time.

Return Value

Returns a string representation of an integer timestamp. In debug mode, returns the current Unix timestamp. In production, returns the file's modification time as a Unix timestamp if the file exists. Falls back to CACHE_BUST_VERSION (a global variable set at application startup) if the file cannot be accessed or doesn't exist. This string is typically appended to static file URLs as a query parameter.

Dependencies

  • flask
  • os
  • time

Required Imports

import os
import time
from flask import Flask

Usage Example

# Setup required globals and Flask app
import os
import time
from flask import Flask

app = Flask(__name__)
app.static_folder = 'static'
DEBUG_MODE = False
CACHE_BUST_VERSION = str(int(time.time()))

# Function definition
def get_file_version(filename):
    if DEBUG_MODE:
        return str(int(time.time()))
    try:
        file_path = os.path.join(app.static_folder, filename)
        if os.path.exists(file_path):
            mtime = os.path.getmtime(file_path)
            return str(int(mtime))
    except (OSError, AttributeError):
        pass
    return CACHE_BUST_VERSION

# Usage examples
version = get_file_version('css/style.css')
print(f"Version for style.css: {version}")

# Typical usage in Flask template context
static_url = f"/static/css/style.css?v={get_file_version('css/style.css')}"
print(f"Static URL with cache busting: {static_url}")

# In Flask route or template context processor
@app.context_processor
def utility_processor():
    return dict(get_file_version=get_file_version)

Best Practices

  • Ensure DEBUG_MODE is properly set based on your environment (True for development, False for production)
  • Initialize CACHE_BUST_VERSION at application startup (e.g., using time.time()) to provide a consistent fallback
  • Make this function available in Flask templates by registering it as a context processor or Jinja2 filter
  • Use the returned version string as a query parameter in static file URLs (e.g., /static/file.css?v=12345678)
  • Ensure app.static_folder is properly configured before calling this function
  • Handle the case where the static folder or files might not exist in development environments
  • Consider using this function in conjunction with Flask's url_for() function for generating static URLs
  • The function gracefully handles file access errors and missing files by falling back to CACHE_BUST_VERSION
  • In production, this approach works best with proper HTTP cache headers set on static files

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_file_version_v1 94.5% 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 get_cache_buster 76.7% 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
  • function debug_cache_info 68.4% 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_template_vars 64.9% similar

    A Flask context processor that injects the get_file_version function into all Jinja2 templates, making it globally available for cache-busting static files.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function touch_static_files 61.7% similar

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

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