0
0
Flaskframework~5 mins

Cache busting strategies in Flask

Choose your learning style9 modes available
Introduction

Cache busting helps your website show the newest files to visitors by avoiding old saved versions in their browsers.

When you update CSS or JavaScript files and want users to see the changes immediately.
When you fix bugs in static files and need browsers to load the fixed versions.
When deploying new versions of your website with updated images or fonts.
When you want to avoid users seeing broken or outdated content due to cached files.
Syntax
Flask
url_for('static', filename='style.css', v='12345')
You add a version or unique string as a query parameter to the static file URL.
Flask's url_for helps generate the correct URL with the cache busting parameter.
Examples
Adds a version date to the JavaScript file URL to force browsers to load the new file.
Flask
url_for('static', filename='app.js', v='20240601')
Uses a hash or unique string as a version to bust cache for the CSS file.
Flask
url_for('static', filename='main.css', v='abcdef')
Appends the current time as a query parameter to always load the latest image (not recommended for production).
Flask
url_for('static', filename='image.png') + '?v=' + str(time.time())
Sample Program

This Flask app serves a simple page that includes CSS and JS files with a version query parameter. This helps browsers load the latest files when the version changes.

Flask
from flask import Flask, render_template_string, url_for
import time

app = Flask(__name__)

@app.route('/')
def index():
    version = '20240601'  # Example version string
    css_url = url_for('static', filename='style.css', v=version)
    js_url = url_for('static', filename='app.js', v=version)
    html = f'''
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Cache Busting Example</title>
        <link rel="stylesheet" href="{css_url}">
    </head>
    <body>
        <h1>Cache Busting with Flask</h1>
        <script src="{js_url}"></script>
    </body>
    </html>
    '''
    return render_template_string(html)

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Use a fixed version string that you update when files change, like a date or a hash.

Avoid using constantly changing values like timestamps in production because it disables caching benefits.

Flask's url_for is the best way to generate URLs for static files with cache busting.

Summary

Cache busting forces browsers to load updated static files by changing their URLs.

Use version query parameters with url_for in Flask to add cache busting.

Update the version string only when files change to keep caching effective.