How to Use Caching in Flask for Faster Web Apps
Use the
Flask-Caching extension to add caching in Flask. Initialize a cache object with your Flask app and use decorators like @cache.cached(timeout=seconds) to cache view results easily.Syntax
To use caching in Flask, first install and import Flask-Caching. Then create a Cache object linked to your Flask app. Use @cache.cached(timeout=seconds) to cache the output of a route for a set time.
Cache(app, config={'CACHE_TYPE': 'simple'}): Initializes cache with simple in-memory storage.@cache.cached(timeout=60): Caches the decorated function's output for 60 seconds.
python
from flask import Flask from flask_caching import Cache app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/') @cache.cached(timeout=60) def index(): return 'Hello, cached world!' if __name__ == '__main__': app.run()
Example
This example shows a Flask app that caches the homepage response for 30 seconds. The first request runs the function, and subsequent requests within 30 seconds return the cached response instantly.
python
from flask import Flask from flask_caching import Cache import time app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/') @cache.cached(timeout=30) def index(): return f"Current time: {time.time()}" if __name__ == '__main__': app.run(debug=True)
Output
Current time: 1686000000.123456 (example output, stays same for 30 seconds)
Common Pitfalls
Common mistakes when using caching in Flask include:
- Not setting a
timeout, causing cached data to never expire. - Using
CACHE_TYPEthat doesn't fit your environment (e.g.,simplecache is not suitable for production). - Forgetting to initialize
Cachewith the Flask app. - Caching dynamic content that should not be cached.
python
from flask import Flask from flask_caching import Cache app = Flask(__name__) # Wrong: missing CACHE_TYPE config cache = Cache(app) @app.route('/') @cache.cached(timeout=60) def index(): return 'Hello' # Correct way: # cache = Cache(app, config={'CACHE_TYPE': 'simple'})
Quick Reference
| Feature | Usage | Notes |
|---|---|---|
| Initialize Cache | cache = Cache(app, config={'CACHE_TYPE': 'simple'}) | Use 'simple' for development, Redis/Memcached for production |
| Cache a route | @cache.cached(timeout=60) | Caches output for 60 seconds |
| Clear cache manually | cache.clear() | Clears all cached data |
| Cache with key prefix | @cache.cached(timeout=60, key_prefix='mykey') | Custom cache key |
| Different cache types | 'simple', 'redis', 'memcached', 'filesystem' | Choose based on your app needs |
Key Takeaways
Use Flask-Caching extension to add caching easily in Flask apps.
Always configure CACHE_TYPE and timeout to control cache behavior.
Cache only data that is safe to reuse to avoid stale or incorrect responses.
For production, use robust cache backends like Redis or Memcached instead of simple memory cache.
Clear cache when needed to refresh data or during deployments.