Registry / web-framework / flask-caching

flask-caching

JSON →
library2.5.0pypypi✓ verified 26d ago

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.

pip install Flask-Caching
INSTALL
IMPORT
SIG · FLASK-CACHING
F
flask-caching
web-frameworkpythonv2.5.0
Install
2.4s avg
Import
484ms
Disk
21MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.4.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.915 runs
installs and imports cleanly · install 0.0s · import 0.505s · 22.9MB
glibc
py 3.103.915 runs
installs and imports cleanly · install 2.4s · import 0.463s · 23MB
21MB installed
● package 21MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Cache
from flask_caching import Cache

This quickstart demonstrates setting up Flask-Caching with a `SimpleCache` backend, caching a simple view function (`/`), and using a custom `make_cache_key` for a dynamic route (`/user/<username>`). It also includes an endpoint to clear the cache. For external backends like Redis or Memcached, ensure the respective `CACHE_TYPE` and configuration variables are set in `app.config` and the necessary dependencies are installed (e.g., `pip install Flask-Caching[redis]` and `pip install redis`).

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)
Debug
Known issues
breakingFlask-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.
fix
Upgrade Flask to 2.0+ (e.g., `pip install Flask>=2.0`) or keep Flask-Caching at v1.x or earlier (e.g., `pip install Flask-Caching==1.11.1`).
affects: 2.0.0+
breakingStarting 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.
fix
Update import statements. For example, change `from flask_caching.ext.redis import RedisCache` to `from flask_caching.backends.rediscache import RedisCache`. Consult the documentation for specific backend import paths.
affects: 2.0.0+
breakingThe `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.
fix
Migrate to an officially supported caching backend such as RedisCache, MemcachedCache, or FileSystemCache. If migration is not feasible, pin Flask-Caching to v1.9.x or older.
affects: 1.10.0+ (deprecated), 2.0.0+ (removed)
gotchaWhen 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`.
fix
Use the `make_cache_key` argument with the `@cache.cached` decorator. Provide a function that generates a unique key based on relevant request attributes, such as `request.path`, `request.args`, or a combination of them. Example: `@cache.cached(timeout=30, make_cache_key=lambda: request.path)`.
affects: all
gotchaIncorrectly 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`.
fix
Carefully review your `app.config` settings for Flask-Caching. Verify that `CACHE_TYPE` corresponds to the desired backend, that the necessary Python packages are installed (e.g., `redis` for RedisCache), and that all required backend-specific configuration variables are correctly set according to the Flask-Caching documentation.
affects: all
gotchaThe test script itself contains a Python SyntaxError related to incorrect f-string usage, preventing the application from starting. This is not a Flask-Caching library issue, but a defect in the test environment or script.
fix
Review and correct the f-string syntax in the test script (e.g., use single quotes for inner strings within a double-quoted f-string, or escape inner quotes). Example: change `strftime("%H:%M:%S")` to `strftime('%H:%M:%S')`.
affects: N/A (specific to the test script syntax, not Flask-Caching versions)
Errors
Common errors & fixes
AttributeError: 'Cache' object has no attribute 'app'
This error typically occurs when the `Cache` object is instantiated without an application instance, or `init_app` is called before the Flask application `app` object is fully created or configured, especially in an application factory pattern. The `Cache` object tries to access `app.config` or `app.jinja_env` (for template caching) but the `app` attribute hasn't been properly set or doesn't have the expected properties yet.
fix
Ensure that the Flask application instance (`app`) is fully initialized before passing it to the `Cache` constructor or calling `cache.init_app(app)`. If using an application factory, pass the `app` instance to `init_app` *after* the `app` has been created. For Dash apps, remember to pass `app.server` to `init_app` instead of `app` directly.

```python
from flask import Flask
from flask_caching import Cache

# Method 1: Pass app during instantiation
app = Flask(__name__)
app.config.from_mapping({
    "CACHE_TYPE": "SimpleCache",
    "CACHE_DEFAULT_TIMEOUT": 300
})
cache = Cache(app=app) # or Cache(app)

# Method 2: Using init_app (recommended for app factories)
# cache = Cache() 
# def create_app():
#     app = Flask(__name__)
#     app.config.from_mapping({
#         "CACHE_TYPE": "SimpleCache",
#         "CACHE_DEFAULT_TIMEOUT": 300
#     })
#     cache.init_app(app)
#     return app

# For Dash applications:
# from dash import Dash
# app = Dash(__name__)
# cache = Cache()
# cache.init_app(app.server)
```
ModuleNotFoundError: No module named 'flask_caching' OR ModuleNotFoundError: No module named 'flask.ext.cache'
The `ModuleNotFoundError` indicates that the Python interpreter cannot find the `flask_caching` package. The `flask.ext.cache` import specifically points to an outdated import path from an older version of Flask-Cache (before Flask 0.8), which has since been deprecated and removed.
fix
First, ensure `flask-caching` is installed correctly in your environment using pip: `pip install Flask-Caching`. If it's installed but still not found, check your Python environment or virtual environment. If the error refers to `flask.ext.cache`, update your import statements to `from flask_caching import Cache` (for the main Cache class) or `from flask_caching import make_template_fragment_key` (for other utilities).

```python
# Incorrect (old/deprecated):
# from flask.ext.cache import Cache

# Correct:
from flask_caching import Cache

# Example usage:
# from flask import Flask
# app = Flask(__name__)
# cache = Cache(app=app, config={'CACHE_TYPE': 'SimpleCache'})
```
Flask-Caching not caching / SimpleCache not working in multi-process environment
When using `CACHE_TYPE: 'SimpleCache'`, Flask-Caching uses a local Python dictionary for storing cached values. This means the cache is tied to a single process. If your Flask application is deployed with a WSGI server (like Gunicorn or uWSGI) that uses multiple worker processes, each process will have its own independent cache, making it appear as if caching is not working or that the cache is constantly being 'recreated' with each request.
fix
For production environments or any setup using multiple worker processes, switch to a distributed caching backend like RedisCache or MemcachedCache. For local development or simple single-process applications, `FileSystemCache` can also be a viable alternative to `SimpleCache` to persist cache across restarts.

```python
# For RedisCache (requires 'redis' library and a running Redis server):
app.config.from_mapping({
    "CACHE_TYPE": "RedisCache",
    "CACHE_REDIS_URL": "redis://localhost:6379/0", # Adjust as needed
    "CACHE_DEFAULT_TIMEOUT": 300
})

# For FileSystemCache (requires a directory for cache files):
# app.config.from_mapping({
#     "CACHE_TYPE": "FileSystemCache",
#     "CACHE_DIR": "/tmp/flask_cache", # Ensure this directory exists and is writable
#     "CACHE_DEFAULT_TIMEOUT": 300
# })

# cache = Cache(app)
```
redis.exceptions.ConnectionError: Error connecting to server OR flask-caching config ignores the redis password
These errors indicate a problem with the Flask-Caching connection to the Redis server. `ConnectionError` means the application cannot establish a connection to Redis, often due to the server not running, incorrect host/port, or network issues. The 'ignores password' issue arises when both `CACHE_REDIS_URL` and `CACHE_REDIS_PASSWORD` are configured; `CACHE_REDIS_URL` can override or incorrectly handle the password if it's not embedded within the URL.
fix
Ensure the Redis server is running and accessible from your application's host and port. Verify the `CACHE_REDIS_HOST`, `CACHE_REDIS_PORT`, and `CACHE_REDIS_DB` configurations are correct. When using a password, it is best practice to include it directly within the `CACHE_REDIS_URL` or ensure `CACHE_REDIS_PASSWORD` is correctly configured *without* a conflicting `CACHE_REDIS_URL` that doesn't include the password.

```python
# If using separate host/port/password configs:
app.config.from_mapping({
    "CACHE_TYPE": "RedisCache",
    "CACHE_REDIS_HOST": "your_redis_host",
    "CACHE_REDIS_PORT": 6379, # Default Redis port
    "CACHE_REDIS_DB": 0,
    "CACHE_REDIS_PASSWORD": "your_redis_password", # Only if required
    "CACHE_DEFAULT_TIMEOUT": 300
})

# Preferred: Using CACHE_REDIS_URL with embedded password if applicable:
# app.config.from_mapping({
#     "CACHE_TYPE": "RedisCache",
#     "CACHE_REDIS_URL": "redis://:your_redis_password@your_redis_host:6379/0",
#     "CACHE_DEFAULT_TIMEOUT": 300
# })

# Ensure 'redis' package is installed: pip install redis
```
Upgrade
Version history
2.5.0latest on PyPI · released Aug 24, 2026
Audit
Dependencies
FlaskrequiredCore web framework integration.
redisoptionalRequired for RedisCache backend.
python-memcachedoptionalRequired for MemcachedCache backend (pylibmc is an alternative).
Agent activity
19 hits · last 30 days
node
16
OpenAI (training)
2
Resources