CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-flask-caching

Adds caching support to Flask applications.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

backends.mddocs/

Cache Backends

Multiple cache storage backends for different deployment scenarios, from simple in-memory caching for development to distributed Redis clusters for production. Each backend implements the same interface while optimizing for specific use cases and infrastructure requirements.

Capabilities

Simple Cache Backend

In-memory cache for single-process development environments. Not thread-safe and data is lost on application restart.

class SimpleCache(BaseCache):
    """
    Simple memory cache for single process environments.
    
    Parameters:
    - threshold: Maximum number of items (default: 500)
    - default_timeout: Default expiration time in seconds (default: 300)
    - ignore_errors: Ignore errors during delete_many operations
    """
    def __init__(
        self, 
        threshold: int = 500, 
        default_timeout: int = 300, 
        ignore_errors: bool = False
    ): ...

Configuration:

app.config['CACHE_TYPE'] = 'SimpleCache'
app.config['CACHE_THRESHOLD'] = 1000
app.config['CACHE_DEFAULT_TIMEOUT'] = 600

# Or use string backend name
app.config['CACHE_TYPE'] = 'simple'

Redis Cache Backend

High-performance Redis-based cache with support for clustering and sentinel configurations.

class RedisCache(BaseCache):
    """
    Redis cache backend for scalable caching.
    
    Parameters:
    - host: Redis server host or Redis client instance
    - port: Redis server port (default: 6379)
    - password: Authentication password
    - db: Database number (default: 0)
    - default_timeout: Default expiration time in seconds
    - key_prefix: Prefix for all cache keys
    - **kwargs: Additional redis.Redis parameters
    """
    def __init__(
        self,
        host: str = "localhost",
        port: int = 6379,
        password: Optional[str] = None,
        db: int = 0,
        default_timeout: int = 300,
        key_prefix: Optional[str] = None,
        **kwargs
    ): ...

class RedisClusterCache(BaseCache):
    """Redis Cluster cache backend for distributed caching."""
    
class RedisSentinelCache(BaseCache):
    """Redis Sentinel cache backend for high availability."""

Configuration:

# Basic Redis configuration
app.config['CACHE_TYPE'] = 'RedisCache'
app.config['CACHE_REDIS_HOST'] = 'localhost'
app.config['CACHE_REDIS_PORT'] = 6379
app.config['CACHE_REDIS_DB'] = 0
app.config['CACHE_REDIS_PASSWORD'] = 'mypassword'

# Redis URL configuration
app.config['CACHE_TYPE'] = 'RedisCache'
app.config['CACHE_REDIS_URL'] = 'redis://localhost:6379/0'

# Redis Cluster
app.config['CACHE_TYPE'] = 'RedisClusterCache'
app.config['CACHE_REDIS_HOST'] = [
    {'host': 'node1.redis.cluster', 'port': 6379},
    {'host': 'node2.redis.cluster', 'port': 6379},
    {'host': 'node3.redis.cluster', 'port': 6379}
]

# Or use string backend names
app.config['CACHE_TYPE'] = 'redis'
app.config['CACHE_TYPE'] = 'rediscluster'
app.config['CACHE_TYPE'] = 'redissentinel'

Memcached Cache Backend

Memcached-based caching with support for multiple servers and SASL authentication.

class MemcachedCache(BaseCache):
    """
    Memcached cache backend.
    
    Parameters:
    - servers: List of memcached servers
    - default_timeout: Default expiration time in seconds
    - key_prefix: Prefix for all cache keys
    """

class SASLMemcachedCache(BaseCache):
    """Memcached cache with SASL authentication support."""
    
class SpreadSASLMemcachedCache(BaseCache):
    """Memcached cache with spread SASL authentication."""

Configuration:

# Single Memcached server
app.config['CACHE_TYPE'] = 'MemcachedCache'
app.config['CACHE_MEMCACHED_SERVERS'] = ['127.0.0.1:11211']

# Multiple Memcached servers
app.config['CACHE_TYPE'] = 'MemcachedCache'
app.config['CACHE_MEMCACHED_SERVERS'] = [
    '192.168.1.100:11211',
    '192.168.1.101:11211',
    '192.168.1.102:11211'
]

# SASL Authentication
app.config['CACHE_TYPE'] = 'SASLMemcachedCache'
app.config['CACHE_MEMCACHED_SERVERS'] = ['127.0.0.1:11211']
app.config['CACHE_MEMCACHED_USERNAME'] = 'myuser'
app.config['CACHE_MEMCACHED_PASSWORD'] = 'mypassword'

# Or use string backend names
app.config['CACHE_TYPE'] = 'memcached'
app.config['CACHE_TYPE'] = 'saslmemcached'
app.config['CACHE_TYPE'] = 'spreadsaslmemcached'

Filesystem Cache Backend

File system-based cache that stores cached data as files on disk. Suitable for shared hosting environments or persistent caching needs.

class FileSystemCache(BaseCache):
    """
    File system cache backend.
    
    Parameters:
    - cache_dir: Directory path for cache files
    - threshold: Maximum number of files (0 = no limit)
    - default_timeout: Default expiration time in seconds
    - mode: File permission mode (default: 0o600)
    - hash_method: Hash function for filename generation
    - ignore_errors: Ignore errors during delete_many operations
    """
    def __init__(
        self,
        cache_dir: str,
        threshold: int = 500,
        default_timeout: int = 300,
        mode: int = 0o600,
        hash_method: Callable = hashlib.md5,
        ignore_errors: bool = False
    ): ...

Configuration:

app.config['CACHE_TYPE'] = 'FileSystemCache'
app.config['CACHE_DIR'] = '/var/cache/myapp'
app.config['CACHE_THRESHOLD'] = 1000
app.config['CACHE_DEFAULT_TIMEOUT'] = 300

# Or use string backend name
app.config['CACHE_TYPE'] = 'filesystem'

Null Cache Backend

No-operation cache backend for testing and development. All cache operations succeed but nothing is actually cached.

class NullCache(BaseCache):
    """
    Null cache backend that performs no caching operations.
    Useful for testing and development environments.
    """

Configuration:

app.config['CACHE_TYPE'] = 'NullCache'
app.config['CACHE_NO_NULL_WARNING'] = True  # Suppress warnings

# Or use string backend name
app.config['CACHE_TYPE'] = 'null'

UWSGI Cache Backend

UWSGI-specific cache backend that leverages UWSGI's built-in caching capabilities.

class UWSGICache(BaseCache):
    """
    UWSGI cache backend using uwsgi.cache_* functions.
    Only available when running under UWSGI server.
    
    Parameters:
    - default_timeout: Default expiration time in seconds (default: 300)
    - cache: Name of the caching instance to connect to (default: "")
    
    Note: This class cannot be used when running under PyPy.
    Note: Requires cache2 to be enabled in uWSGI configuration.
    """
    def __init__(self, default_timeout: int = 300, cache: str = ""): ...

Configuration:

app.config['CACHE_TYPE'] = 'flask_caching.contrib.uwsgicache.UWSGICache'
app.config['CACHE_UWSGI_NAME'] = 'mycache'

# Legacy path (deprecated)
app.config['CACHE_TYPE'] = 'UWSGICache'
app.config['CACHE_UWSGI_NAME'] = 'mycache'

# Or use string backend name
app.config['CACHE_TYPE'] = 'uwsgi'

Google Cloud Storage Cache Backend

Cloud-based cache backend using Google Cloud Storage buckets. User-contributed functionality for distributed caching in Google Cloud environments.

class GoogleCloudStorageCache(BaseCache):
    """
    Google Cloud Storage cache backend.
    
    Parameters:
    - bucket: GCS bucket name (must already exist)
    - key_prefix: Prefix for all cache keys
    - default_timeout: Default expiration time in seconds
    - delete_expired_objects_on_read: Delete expired objects on read
    - anonymous: Use anonymous credentials (for testing)
    - **kwargs: Additional google.cloud.storage.Client parameters
    """
    def __init__(
        self,
        bucket: str,
        key_prefix: Optional[str] = None,
        default_timeout: int = 300,
        delete_expired_objects_on_read: bool = False,
        anonymous: bool = False,
        **kwargs
    ): ...

Configuration:

app.config['CACHE_TYPE'] = 'flask_caching.contrib.GoogleCloudStorageCache'
app.config['CACHE_GCS_BUCKET'] = 'my-cache-bucket'
app.config['CACHE_GCS_KEY_PREFIX'] = 'myapp_cache_'

# Custom configuration
cache = Cache(app, config={
    'CACHE_TYPE': 'flask_caching.contrib.GoogleCloudStorageCache',
    'CACHE_GCS_BUCKET': 'my-cache-bucket',
    'CACHE_GCS_DELETE_EXPIRED_ON_READ': True
})

Base Cache Class

All cache backends inherit from BaseCache, which defines the common interface.

class BaseCache:
    """
    Base class for all cache backends.
    
    Parameters:
    - default_timeout: Default expiration time in seconds (default: 300)
    """
    def __init__(self, default_timeout: int = 300): ...
    
    @classmethod
    def factory(cls, app, config, args, kwargs):
        """Factory method for creating cache instances."""
        
    def get(self, key: str) -> Any: ...
    def set(self, key: str, value: Any, timeout: Optional[int] = None) -> Optional[bool]: ...
    def add(self, key: str, value: Any, timeout: Optional[int] = None) -> bool: ...
    def delete(self, key: str) -> bool: ...
    def delete_many(self, *keys) -> List[str]: ...
    def has(self, key: str) -> bool: ...
    def clear(self) -> bool: ...
    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]: ...

Custom Backend Implementation

Create custom cache backends by inheriting from BaseCache:

from flask_caching.backends.base import BaseCache

class MyCustomCache(BaseCache):
    def __init__(self, custom_param=None, **kwargs):
        super().__init__(**kwargs)
        self.custom_param = custom_param
        
    @classmethod
    def factory(cls, app, config, args, kwargs):
        kwargs.update({
            'custom_param': config.get('CACHE_CUSTOM_PARAM')
        })
        return cls(*args, **kwargs)
        
    def get(self, key):
        # Custom get implementation
        pass
        
    def set(self, key, value, timeout=None):
        # Custom set implementation
        pass
        
    # Implement other required methods...

# Register custom backend
app.config['CACHE_TYPE'] = 'myapp.cache.MyCustomCache'

Backend Selection Guidelines

Development:

  • SimpleCache - Quick setup, no external dependencies
  • NullCache - Testing without caching side effects

Production:

  • RedisCache - High performance, rich features, horizontal scaling
  • MemcachedCache - Simple, fast, well-established
  • FileSystemCache - Shared hosting, persistent cache across restarts

High Availability:

  • RedisClusterCache - Distributed Redis setup
  • RedisSentinelCache - Redis with automatic failover
  • Multiple MemcachedCache servers with consistent hashing

Specialized:

  • UWSGICache - When using UWSGI server with built-in caching
  • Custom backends - Specific infrastructure requirements

Install with Tessl CLI

npx tessl i tessl/pypi-flask-caching

docs

backends.md

core-operations.md

decorators.md

index.md

template-caching.md

tile.json