How to Use Flask-Caching: Simple Guide with Examples
To use
flask-caching, first install it and then create a Cache object linked to your Flask app. Use decorators like @cache.cached(timeout=seconds) on routes or functions to store their output temporarily and speed up responses.Syntax
The basic syntax involves importing Cache from flask_caching, initializing it with your Flask app, and then using decorators to cache function outputs.
Cache(app, config={'CACHE_TYPE': 'simple'}): Creates a cache instance with a simple in-memory cache.@cache.cached(timeout=60): Decorator to cache the output of a view or function for 60 seconds.cache.set(key, value, timeout=seconds): Manually store a value in cache.cache.get(key): Retrieve a cached value by key.
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 output 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
When you visit http://localhost:5000 multiple times within 30 seconds, the displayed time stays the same because the response is cached. After 30 seconds, it updates to the new current time.
Common Pitfalls
- Not initializing
Cachewith the Flask app before using decorators causes errors. - Using a cache type that doesn't fit your environment (e.g.,
simplecache is not suitable for production). - Forgetting to set a
timeoutleads to indefinite caching or no caching. - Trying to cache functions with changing inputs without using
@cache.memoizeor custom keys.
python
from flask import Flask from flask_caching import Cache app = Flask(__name__) cache = Cache() # Missing app initialization @app.route('/') @cache.cached(timeout=60) def index(): return 'Hello' # Correct way: # cache = Cache(app, config={'CACHE_TYPE': 'simple'})
Quick Reference
| Method/Decorator | Purpose | Example Usage |
|---|---|---|
| Cache(app, config) | Initialize cache with Flask app | cache = Cache(app, config={'CACHE_TYPE': 'simple'}) |
| @cache.cached(timeout=seconds) | Cache route or function output | @cache.cached(timeout=60) |
| cache.set(key, value, timeout) | Manually store a value | cache.set('mykey', 'value', timeout=120) |
| cache.get(key) | Retrieve cached value | cache.get('mykey') |
| @cache.memoize(timeout=seconds) | Cache function with arguments | @cache.memoize(timeout=60) |
Key Takeaways
Initialize Cache with your Flask app before using caching decorators.
Use @cache.cached with a timeout to cache route outputs easily.
Choose the right CACHE_TYPE for your environment; 'simple' is for development only.
Use cache.set and cache.get for manual caching control.
Avoid caching functions with changing inputs without memoization or custom keys.