Flask-Caching
Flask-Caching adds comprehensive caching support to Flask applications, providing various backend options such as SimpleCache, RedisCache, MemcachedCache, FileSystemCache, and others. It integrates seamlessly with Flask applications to cache view functions or parts of templates. The current version is 2.3.1, and the library maintains an active release cadence with regular updates and patches.
Warnings
- breaking Flask-Caching v2.0.0 and newer versions require Flask 2.0 or higher. Applications running older Flask versions (e.g., Flask 1.x) must either upgrade Flask or stick to Flask-Caching v1.x to maintain compatibility.
- breaking Starting with v2.0.0, the import paths for many cache backends have changed. Previously, backends like `RedisCache` were often imported from `flask_caching.ext.redis`. The `ext` module has been removed, and all backends are now located under `flask_caching.backends.<backend_name_module>`. This is a significant change requiring update of import statements.
- breaking The `uwsgicache` backend was deprecated in Flask-Caching v1.10.0 and completely removed in v2.0.0. If your application relies on this backend, it will break when upgrading to v2.0.0 or later.
- gotcha When caching dynamic routes (e.g., `/user/<int:user_id>`), the default cache key generation might not always produce unique keys for different parameters, potentially leading to stale or incorrect data being served. It's crucial to explicitly define a custom `make_cache_key`.
- gotcha Incorrectly configuring the `CACHE_TYPE` or its associated parameters (e.g., `CACHE_REDIS_HOST`, `CACHE_MEMCACHED_SERVERS`) is a common source of errors. Ensure the chosen backend library is installed and its configuration matches the chosen `CACHE_TYPE`.
Install
-
pip install Flask-Caching -
pip install Flask-Caching[redis] -
pip install Flask-Caching[memcached]
Imports
- Cache
from flask_caching import Cache
Quickstart
from flask import Flask, request
from flask_caching import Cache
import datetime
app = Flask(__name__)
# Example Configuration (using SimpleCache, good for development)
# For production, consider 'RedisCache', 'MemcachedCache', etc.
app.config.from_mapping({
"CACHE_TYPE": "SimpleCache", # Type of cache to use (e.g., SimpleCache, RedisCache, MemcachedCache)
"CACHE_DEFAULT_TIMEOUT": 300 # Default timeout in seconds for cached items
# For RedisCache: "CACHE_REDIS_HOST": "localhost", "CACHE_REDIS_PORT": 6379
})
cache = Cache(app)
@app.route("/")
@cache.cached(timeout=60) # Cache this view for 60 seconds
def index():
# This part will only execute once every 60 seconds
current_time = datetime.datetime.now().strftime("%H:%M:%S")
return f"<h1>Hello, Flask-Caching!</h1><p>The time is: {current_time}</p><p>This page is cached.</p>"
@app.route("/reset_cache")
def reset_cache():
cache.clear()
return "Cache cleared!"
# Example with dynamic URL and custom cache key
@app.route("/user/<username>")
@cache.cached(timeout=30, make_cache_key=lambda: request.path)
def user_profile(username):
# Simulate a database lookup
import time
time.sleep(2)
return f"<h2>Profile for {username}</h2><p>Data fetched at {datetime.datetime.now().strftime("%H:%M:%S")}</p>"
if __name__ == '__main__':
app.run(debug=True)