Performance: Response caching strategies
Response caching affects how fast the server can deliver content and reduces load on the server and network, improving page load speed.
from flask import Flask, jsonify, make_response import time app = Flask(__name__) cache = {} @app.route('/data') def data(): if 'result' in cache and time.time() - cache['time'] < 60: response = make_response(jsonify(cache['result'])) response.headers['Cache-Control'] = 'public, max-age=60' return response result = expensive_computation() cache['result'] = result cache['time'] = time.time() response = make_response(jsonify(result)) response.headers['Cache-Control'] = 'public, max-age=60' return response
from flask import Flask, jsonify app = Flask(__name__) @app.route('/data') def data(): # No caching, recomputes every request result = expensive_computation() return jsonify(result)
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching, recompute every request | N/A (server-side) | N/A | Increases LCP due to slow response | [X] Bad |
| Server-side caching with Cache-Control headers | N/A (server-side) | N/A | Faster LCP due to quick response | [OK] Good |
@cache.cached with a named argument timeout=60 to set cache duration.cache.cache which is invalid. @cached(60)
def my_route():
return 'Hello' misses the cache. instance prefix.get_data() within 30 seconds?
@cache.cached(timeout=30)
def get_data():
print('Fetching data...')
return 'Data'@cache.cached(timeout=60)
def index():
return render_template('index.html')
# Later in code
cache = Cache(app, config={'CACHE_TYPE': 'simple'})@cache.cached uses the cache object, but it is created after the function definition, so cache is undefined at decoration time.render_template output can be cached. 'simple' cache type is valid for development.@cache.cached(timeout=60, key_prefix=lambda: f'user_{current_user.id}') uses a lambda returning a string with the current user's ID, ensuring unique cache per user. Use @cache.cached(timeout=60, key_prefix=lambda: request.path) uses request path only, same for all users. Use @cache.cached(timeout=60, key_prefix=lambda: request.args) uses request arguments, which may not include user ID. Use @cache.cached(timeout=60) without key_prefix uses default key, same for all users.Pass the test and this pattern moves unknown