or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

backends.mdcore-operations.mddecorators.mdindex.mdtemplate-caching.md
tile.json

tessl/pypi-flask-caching

Adds caching support to Flask applications.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/flask-caching@2.3.x

To install, run

npx @tessl/cli install tessl/pypi-flask-caching@2.3.0

index.mddocs/

Flask-Caching

A 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.

Package Information

  • Package Name: Flask-Caching
  • Language: Python
  • Installation: pip install Flask-Caching

Core Imports

from flask_caching import Cache

For specific functionality:

from flask_caching import Cache, CachedResponse, make_template_fragment_key

Basic Usage

from 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()

Architecture

Flask-Caching follows a modular architecture with clear separation of concerns:

  • Cache Class: Central controller managing cache operations and configuration
  • Backend System: Pluggable cache storage backends (Redis, Memcached, filesystem, etc.)
  • Decorator Layer: Function and view decorators (@cached, @memoize) for transparent caching
  • Jinja2 Integration: Template fragment caching through custom Jinja2 extension
  • Configuration Management: Flask app configuration integration with sensible defaults

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.

Capabilities

Core Cache Operations

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]: ...

Core Operations

Caching Decorators

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: ...

Decorators

Cache Backends

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): ...

Backends

Template Fragment Caching

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 %}

Template Caching

Types

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]: ...

Configuration

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 dictionary
  • CACHE_ARGS - Additional cache arguments list

Redis 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 password
  • CACHE_REDIS_URL - Redis connection URL
  • CACHE_REDIS_SENTINELS - Redis Sentinel servers list
  • CACHE_REDIS_SENTINEL_MASTER - Redis Sentinel master name
  • CACHE_REDIS_SENTINEL_PASSWORD - Redis Sentinel password
  • CACHE_REDIS_CLUSTER - Redis Cluster connection string

Memcached Options:

  • CACHE_MEMCACHED_SERVERS - List of Memcached servers
  • CACHE_MEMCACHED_USERNAME - SASL username (for SASLMemcachedCache)
  • CACHE_MEMCACHED_PASSWORD - SASL password (for SASLMemcachedCache)

Filesystem Options:

  • CACHE_DIR - Directory for filesystem cache

UWSGI Options:

  • CACHE_UWSGI_NAME - UWSGI cache name