Adds caching support to Flask applications.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Direct cache manipulation methods that provide fine-grained control over cached data. These operations form the foundation for all Flask-Caching functionality and allow direct interaction with the underlying cache backend.
Retrieve cached values by key. Returns None if the key doesn't exist or has expired.
def get(key: str) -> Any:
"""
Retrieve a value from the cache.
Parameters:
- key: Cache key to retrieve
Returns:
The cached value or None if not found
"""Usage:
# Get a single value
user_data = cache.get('user:123')
if user_data is None:
user_data = fetch_user_from_database(123)
cache.set('user:123', user_data, timeout=300)
# Get with fallback handling
settings = cache.get('app_settings')
if settings is None:
settings = {}Store values in the cache with optional timeout. Returns True if successful, False otherwise.
def set(key: str, value: Any, timeout: Optional[int] = None) -> Optional[bool]:
"""
Store a value in the cache.
Parameters:
- key: Cache key to store under
- value: Value to cache (must be serializable)
- timeout: Expiration time in seconds (None uses default timeout)
Returns:
True if successful, False otherwise, None for some backends
"""Usage:
# Set with default timeout
cache.set('user:123', user_data)
# Set with custom timeout (5 minutes)
cache.set('temp_token', token, timeout=300)
# Set with no expiration
cache.set('permanent_config', config, timeout=0)Check if a key exists in the cache without retrieving its value.
def has(key: str) -> bool:
"""
Check if a key exists in the cache.
Parameters:
- key: Cache key to check
Returns:
True if key exists, False otherwise
"""Usage:
if cache.has('user:123'):
user_data = cache.get('user:123')
else:
user_data = fetch_user_from_database(123)
cache.set('user:123', user_data)Add a value only if the key doesn't already exist. Atomic operation that prevents overwriting existing values.
def add(key: str, value: Any, timeout: Optional[int] = None) -> bool:
"""
Add a value to the cache only if key doesn't exist.
Parameters:
- key: Cache key to store under
- value: Value to cache
- timeout: Expiration time in seconds
Returns:
True if value was added, False if key already exists
"""Usage:
# Atomic cache-or-compute pattern
if cache.add('computation_result:abc', None, timeout=3600):
# We got the lock, compute the result
result = expensive_computation('abc')
cache.set('computation_result:abc', result, timeout=3600)
else:
# Another process is computing, wait and get result
result = cache.get('computation_result:abc')Remove specific keys or multiple keys from the cache.
def delete(key: str) -> bool:
"""
Delete a key from the cache.
Parameters:
- key: Cache key to delete
Returns:
True if key was deleted, False if key didn't exist
"""
def delete_many(*keys) -> List[str]:
"""
Delete multiple keys from the cache.
Parameters:
- keys: Variable number of cache keys to delete
Returns:
List of successfully deleted keys
"""Usage:
# Delete single key
cache.delete('user:123')
# Delete multiple keys
deleted_keys = cache.delete_many('user:123', 'user:456', 'user:789')
print(f"Deleted {len(deleted_keys)} keys")Remove all cached values. Use with caution in production environments.
def clear() -> bool:
"""
Clear all cached values.
Returns:
True if cache was cleared successfully
"""Usage:
# Clear all cached data
cache.clear()Efficient operations for working with multiple cache keys simultaneously.
def get_many(*keys) -> List[Any]:
"""
Get multiple values from cache.
Parameters:
- keys: Variable number of cache keys
Returns:
List of values in same order as keys (None for missing keys)
"""
def set_many(mapping: Dict[str, Any], timeout: Optional[int] = None) -> List[Any]:
"""
Set multiple key-value pairs.
Parameters:
- mapping: Dictionary of key-value pairs to cache
- timeout: Expiration time for all keys
Returns:
List of results for each set operation
"""
def get_dict(*keys) -> Dict[str, Any]:
"""
Get multiple values as a dictionary.
Parameters:
- keys: Variable number of cache keys
Returns:
Dictionary mapping keys to values (excludes missing keys)
"""Usage:
# Bulk get operations
user_ids = ['user:123', 'user:456', 'user:789']
user_data_list = cache.get_many(*user_ids)
user_data_dict = cache.get_dict(*user_ids)
# Bulk set operations
cache.set_many({
'user:123': user_123_data,
'user:456': user_456_data,
'user:789': user_789_data
}, timeout=300)Additional operations available when using Redis backends.
def unlink(*keys) -> List[str]:
"""
Redis UNLINK command for non-blocking key deletion.
Falls back to delete_many for non-Redis backends.
Parameters:
- keys: Variable number of cache keys to unlink
Returns:
List of successfully unlinked keys
"""Usage:
# Non-blocking deletion for large values (Redis only)
cache.unlink('large_dataset:processed', 'large_dataset:raw')Install with Tessl CLI
npx tessl i tessl/pypi-flask-caching