Serving high-traffic web applications requires minimizing redundant database queries and expensive computations. If 10,000 users request your course catalog homepage every minute, running the exact same SQL queries 10,000 times wastes database CPU and degrades response times.
Flask-Caching is the standard extension for caching view responses, database query results, and arbitrary Python functions using in-memory caches or Redis.
NullCache: Disables caching entirely (useful for testing).
2. Caching Entire View Responses (@cache.cached)
To cache the full HTML or JSON output of a route:
1@app.route("/api/v1/stats")
2@cache.cached(timeout=60)# Cached for 60 seconds
3defget_global_statistics():
4# Simulated heavy aggregation query across millions of rows
5 stats ={
6"total_students": Student.query.count(),
7"total_courses": Course.query.count(),
8"active_enrollments":14250
9}
10return jsonify(stats)
The first request executes the database query and stores the output in Redis. All subsequent requests for the next 60 seconds return directly from Redis in under 3 milliseconds!
If your endpoint accepts query parameters (like pagination or search filters), you must set query_string=True so different query strings create distinct cache keys:
1@app.route("/courses")
2@cache.cached(timeout=120, query_string=True)
3deflist_courses():
4# /courses?page=1 and /courses?page=2 get cached separately!