Adds caching support to Flask applications.
npx @tessl/cli install tessl/pypi-flask-caching@2.3.0A Python library that adds comprehensive caching support to Flask web applications. Flask-Caching provides decorators for view and function caching, multiple cache backends (Redis, Memcached, filesystem, in-memory), and template fragment caching capabilities.
pip install Flask-Cachingfrom flask_caching import CacheFor specific functionality:
from flask_caching import Cache, CachedResponse, make_template_fragment_keyfrom flask import Flask
from flask_caching import Cache
app = Flask(__name__)
# Configure cache
app.config['CACHE_TYPE'] = 'SimpleCache' # In-memory cache
app.config['CACHE_DEFAULT_TIMEOUT'] = 300
# Initialize cache
cache = Cache(app)
# Use caching decorator on a view
@app.route('/expensive-operation')
@cache.cached(timeout=60)
def expensive_operation():
# Simulate expensive computation
result = perform_complex_calculation()
return f"Result: {result}"
# Use memoize decorator for functions with arguments
@cache.memoize(timeout=120)
def calculate_fibonacci(n):
if n <= 1:
return n
return calculate_fibonacci(n-1) + calculate_fibonacci(n-2)
if __name__ == '__main__':
app.run()Flask-Caching follows a modular architecture with clear separation of concerns:
This design enables flexible caching strategies, from simple in-memory caching for development to distributed Redis clusters for production, while maintaining a consistent API across all backends.
Direct cache manipulation methods for storing, retrieving, and managing cached data. These operations form the foundation for all caching functionality and provide fine-grained control over cache behavior.
def get(key: str) -> Any: ...
def set(key: str, value: Any, timeout: Optional[int] = None) -> Optional[bool]: ...
def delete(key: str) -> bool: ...
def clear() -> bool: ...
def has(key: str) -> bool: ...
def add(key: str, value: Any, timeout: Optional[int] = None) -> bool: ...
def delete_many(*keys) -> List[str]: ...
def get_many(*keys) -> List[Any]: ...
def set_many(mapping: Dict[str, Any], timeout: Optional[int] = None) -> List[Any]: ...
def get_dict(*keys) -> Dict[str, Any]: ...
def unlink(*keys) -> List[str]: ...Function and view decorators that provide transparent caching capabilities. The @cached decorator caches view results, while @memoize caches function results based on arguments.
def cached(
timeout: Optional[int] = None,
key_prefix: str = "view/%s",
unless: Optional[Callable] = None,
forced_update: Optional[Callable] = None,
response_filter: Optional[Callable] = None,
query_string: bool = False,
hash_method: Callable = hashlib.md5,
cache_none: bool = False,
make_cache_key: Optional[Callable] = None,
source_check: Optional[bool] = None,
response_hit_indication: Optional[bool] = False
) -> Callable: ...
def memoize(
timeout: Optional[int] = None,
make_name: Optional[Callable] = None,
unless: Optional[Callable] = None,
forced_update: Optional[Callable] = None,
response_filter: Optional[Callable] = None,
hash_method: Callable = hashlib.md5,
cache_none: bool = False,
source_check: Optional[bool] = None,
args_to_ignore: Optional[Any] = None
) -> Callable: ...Multiple cache storage backends for different deployment scenarios, from simple in-memory caching to distributed Redis clusters. Each backend provides the same interface while optimizing for specific use cases.
class SimpleCache(BaseCache): ...
class RedisCache(BaseCache): ...
class RedisClusterCache(BaseCache): ...
class RedisSentinelCache(BaseCache): ...
class MemcachedCache(BaseCache): ...
class FileSystemCache(BaseCache): ...
class NullCache(BaseCache): ...
class UWSGICache(BaseCache): ...
class GoogleCloudStorageCache(BaseCache): ...Jinja2 template integration for caching expensive template fragments. Provides template-level caching control with configurable cache keys and timeouts.
def make_template_fragment_key(
fragment_name: str,
vary_on: Optional[List[str]] = None
) -> str: ...Template syntax:
{% cache timeout key1[, key2, ...] %}
...template content...
{% endcache %}class Cache:
def __init__(
self,
app: Optional[Flask] = None,
with_jinja2_ext: bool = True,
config=None
) -> None: ...
def init_app(self, app: Flask, config=None) -> None: ...
@property
def cache(self) -> BaseCache: ...
"""Access to the underlying cache backend instance."""
class CachedResponse(Response):
timeout: Optional[int]
def __init__(self, response, timeout): ...
class BaseCache:
def __init__(self, default_timeout: int = 300): ...
def get(self, key: str) -> Any: ...
def set(self, key: str, value: Any, timeout: Optional[int] = None) -> Optional[bool]: ...
def delete(self, key: str) -> bool: ...
def clear(self) -> bool: ...
def has(self, key: str) -> bool: ...
def add(self, key: str, value: Any, timeout: Optional[int] = None) -> bool: ...
def delete_many(self, *keys) -> List[str]: ...
def get_many(self, *keys) -> List[Any]: ...
def set_many(self, mapping: Dict[str, Any], timeout: Optional[int] = None) -> List[Any]: ...
def get_dict(self, *keys) -> Dict[str, Any]: ...Flask-Caching supports extensive configuration options:
General Options:
CACHE_TYPE - Backend type ('SimpleCache', 'RedisCache', 'filesystem', etc.)CACHE_DEFAULT_TIMEOUT - Default cache timeout in seconds (default: 300)CACHE_KEY_PREFIX - Prefix for all cache keys (default: 'flask_cache_')CACHE_THRESHOLD - Maximum cache items before cleanup (default: 500)CACHE_IGNORE_ERRORS - Whether to ignore cache backend errors (default: False)CACHE_SOURCE_CHECK - Include source code in cache keys (default: False)CACHE_NO_NULL_WARNING - Suppress null cache warnings (default: False)CACHE_OPTIONS - Additional cache options dictionaryCACHE_ARGS - Additional cache arguments listRedis Options:
CACHE_REDIS_HOST - Redis server host (default: 'localhost')CACHE_REDIS_PORT - Redis server port (default: 6379)CACHE_REDIS_DB - Redis database number (default: 0)CACHE_REDIS_PASSWORD - Redis authentication passwordCACHE_REDIS_URL - Redis connection URLCACHE_REDIS_SENTINELS - Redis Sentinel servers listCACHE_REDIS_SENTINEL_MASTER - Redis Sentinel master nameCACHE_REDIS_SENTINEL_PASSWORD - Redis Sentinel passwordCACHE_REDIS_CLUSTER - Redis Cluster connection stringMemcached Options:
CACHE_MEMCACHED_SERVERS - List of Memcached serversCACHE_MEMCACHED_USERNAME - SASL username (for SASLMemcachedCache)CACHE_MEMCACHED_PASSWORD - SASL password (for SASLMemcachedCache)Filesystem Options:
CACHE_DIR - Directory for filesystem cacheUWSGI Options:
CACHE_UWSGI_NAME - UWSGI cache name