Consider this Flask route that sets cache headers:
from flask import Flask, make_response
app = Flask(__name__)
@app.route('/data')
def data():
response = make_response('Hello World')
response.headers['Cache-Control'] = 'public, max-age=60'
return responseWhat will the browser do with the response?
from flask import Flask, make_response app = Flask(__name__) @app.route('/data') def data(): response = make_response('Hello World') response.headers['Cache-Control'] = 'public, max-age=60' return response
Look at the meaning of 'public' and 'max-age' in Cache-Control headers.
The 'Cache-Control: public, max-age=60' header tells browsers and shared caches to store the response for 60 seconds. 'Public' means it can be cached by any cache, including shared ones.
Given this Flask route using Flask-Caching:
from flask import Flask
from flask_caching import Cache
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'SimpleCache'})
@app.route('/time')
@cache.cached(timeout=30)
def get_time():
import time
return str(time.time())What happens when you call /time multiple times within 30 seconds?
from flask import Flask from flask_caching import Cache app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'SimpleCache'}) @app.route('/time') @cache.cached(timeout=30) def get_time(): import time return str(time.time())
Think about what @cache.cached with timeout does.
The @cache.cached decorator caches the function output for the specified timeout. Here, the first call stores the time string, and calls within 30 seconds return the cached value.
Which code snippet correctly sets HTTP headers to prevent caching of a Flask response?
Look for headers that explicitly prevent caching.
'no-store' and 'no-cache' instruct browsers and caches not to store or reuse the response. 'must-revalidate' forces validation. 'max-age=0' means the response is immediately stale.
Consider this Flask route using Flask-Caching:
from flask import Flask
from flask_caching import Cache
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'NullCache'})
@app.route('/data')
@cache.cached(timeout=60)
def data():
return 'Cached Data'Why does caching not occur?
from flask import Flask from flask_caching import Cache app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'NullCache'}) @app.route('/data') @cache.cached(timeout=60) def data(): return 'Cached Data'
Check the meaning of 'NullCache' in Flask-Caching.
NullCache is a cache type that disables caching completely. It never stores or returns cached data, so the function runs every time.
You have a Flask app serving user dashboards with personalized data that changes frequently. Which caching strategy is best to improve performance without showing wrong data?
Think about caching personalized data safely.
Server-side caching keyed by user ID allows caching per user, avoiding data leaks between users and improving performance. Public caching shares data across users, which is unsafe for personalized content.