What is the main reason to implement cache busting strategies in a Flask web application?
Think about how browsers handle static files and updates.
Cache busting forces browsers to fetch updated static files by changing their URLs, avoiding stale cached versions.
Given this Flask template code snippet, what will be the rendered URL for the static file if the file's last modified time is 1680000000?
<link rel="stylesheet" href="{{ url_for('static', filename='style.css', v=timestamp) }}">Assume timestamp = 1680000000.
Look at the query parameter name used in the code.
The url_for function adds the v query parameter with the timestamp value, resulting in /static/style.css?v=1680000000.
Which of the following Flask template snippets correctly adds a cache busting query parameter using the file's last modified time?
{% raw %}{% set timestamp = os.path.getmtime('static/app.js') %}
<script src="{{ url_for('static', filename='app.js', v=timestamp) }}"></script>{% endraw %}Remember that template code cannot call Python functions directly without context.
Option C correctly sets the timestamp in a template variable and passes it as a query parameter in url_for. Other options either misuse Python calls or append query parameters incorrectly.
Consider this Flask route snippet:
from flask import Flask, url_for, render_template
import os
app = Flask(__name__)
@app.route('/')
def index():
timestamp = os.path.getmtime('static/style.css')
return render_template('index.html', timestamp=timestamp)And the template snippet:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css', v=timestamp) }}">Users report their browsers still load old CSS after updates. What is the most likely reason?
Check how file paths are resolved in Python.
If the path to 'static/style.css' is wrong, getmtime will fail or return an old timestamp, so the URL does not change and cache busting fails.
Given this Flask app snippet:
from flask import Flask, url_for, render_template
import os
app = Flask(__name__)
@app.context_processor
def inject_timestamp():
try:
timestamp = int(os.path.getmtime('static/main.js'))
except FileNotFoundError:
timestamp = 0
return dict(timestamp=timestamp)
@app.route('/')
def index():
return render_template('index.html')And this template snippet:
<script src="{{ url_for('static', filename='main.js', v=timestamp) }}"></script>What will be the output URL if the file static/main.js was last modified at UNIX timestamp 1681234567?
Consider how the context processor injects variables into templates.
The context processor adds timestamp to all templates. Since the file exists, its last modified time is used as the query parameter value.