dogpile-cache

1.5.0 · active · verified Fri Apr 10

dogpile.cache is a Python caching API, currently at version 1.5.0, designed to prevent the 'cache stampede' or 'dogpile effect' by using a coordinated locking mechanism. It provides a generic interface to various caching backends (e.g., Redis, Memcached, DBM, Valkey, in-memory) through configurable 'cache regions.' The library emphasizes a succinct API for defining cache characteristics, including storage, expiration, and custom key generation, supporting both direct `get_or_create` and function decorator patterns. It is actively developed with a consistent release cadence, offering robust solutions for managing cache invalidation and data regeneration in high-concurrency environments.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a cache region with the DBM file-based backend and use the `@region.cache_on_arguments()` decorator to cache the result of an expensive function. Subsequent calls with the same arguments will retrieve the cached value until it expires.

from dogpile.cache import make_region
import time
import os

# Configure a region using the DBM backend (file-based cache)
# Replace with 'dogpile.cache.redis' or 'dogpile.cache.pylibmc' for other backends
region = make_region(name='my_cache').configure(
    backend='dogpile.cache.dbm',
    expiration_time=3600, # seconds
    arguments={'filename': 'cache.dbm'}
)

@region.cache_on_arguments()
def get_expensive_data(param1, param2):
    """Simulate an expensive computation."""
    print(f"--- Computing data for {param1}, {param2} ---")
    time.sleep(1) # Simulate work
    return f"Data for {param1}-{param2} at {time.time()}"

print("First call (should compute):")
print(get_expensive_data("arg_a", 1))

print("Second call (should be cached):")
print(get_expensive_data("arg_a", 1))

print("Third call with different arguments (should compute):")
print(get_expensive_data("arg_b", 2))

# Clean up the cache file created for the DBM backend
if os.path.exists('cache.dbm'):
    os.remove('cache.dbm')

view raw JSON →