0
0
Flaskframework~30 mins

Cache busting strategies in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Cache Busting Strategies in Flask
📖 Scenario: You are building a Flask web app that serves static files like CSS and JavaScript. Browsers often cache these files, so when you update them, users might still see the old versions. To fix this, you want to add a cache busting strategy that changes the URL of static files whenever they are updated.
🎯 Goal: Build a simple Flask app that uses a cache busting technique by appending a timestamp query parameter to static file URLs. This ensures browsers load the latest files after updates.
📋 What You'll Learn
Create a Flask app with a route for the homepage
Add a helper function to generate cache-busted URLs for static files
Use the helper function in the HTML template to load CSS and JS files
Ensure the cache busting uses the file's last modified time
💡 Why This Matters
🌍 Real World
Web developers use cache busting to ensure users always get the latest versions of CSS and JavaScript files after updates, avoiding stale cached files.
💼 Career
Understanding cache busting is important for frontend and backend developers to improve user experience and reduce bugs caused by outdated static assets.
Progress0 / 4 steps
1
Set up the Flask app and static folder
Create a Flask app by importing Flask and initializing it with app = Flask(__name__). Also, create a route for '/' that returns a simple HTML string with a link to a CSS file at /static/style.css.
Flask
Need a hint?

Import Flask, create app, and define a route '/' that returns HTML with a CSS link.

2
Add a helper function to generate cache-busted URLs
Import os and flask modules. Define a function called static_file(filename) that gets the file path using os.path.join(app.static_folder, filename). Then get the file's last modified time with os.path.getmtime() and return a string with the filename plus a query parameter ?v= followed by the modification time as an integer.
Flask
Need a hint?

Use os.path.getmtime to get the file's last modified time and append it as a query parameter.

3
Use the helper function in the HTML template
Modify the home() function to import flask and use flask.Markup to safely return HTML. Use the static_file function to generate the CSS file URL inside the HTML string. Replace the static href /static/style.css with the cache-busted URL from static_file('style.css').
Flask
Need a hint?

Use Markup to safely return HTML and call static_file('style.css') to get the cache-busted URL.

4
Complete the app with run command and test
Add the standard Flask app run block at the bottom: if __name__ == '__main__': and inside it call app.run(debug=True). This will start the Flask development server with debug mode enabled.
Flask
Need a hint?

Add the standard Flask run block to start the server with debug mode.