DiskCache is a pure-Python, thread-safe, and process-safe disk-backed persistent cache. It supports various data types, cache eviction policies, and can be used in web servers, for caching slow function results, and in batch jobs. The library is actively maintained with regular updates.
pip install diskcacheVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to initialize a DiskCache instance, store and retrieve data, and clean up the cache directory. It uses a context manager (`with Cache(...)`) for proper cache management and shows basic `set` and `get` operations. A `size_limit` is included as a best practice.
Clear your existing cache directory before upgrading to DiskCache v5.0.0 or later. For example, delete the directory specified in `Cache('/path/to/cache')`. If data migration is critical, use a prior version to export data and then re-import it after upgrading.Ensure all objects are JSON-serializable. For custom objects, implement `__json__` or provide a custom serializer function. For types like `datetime`, convert them to strings (ISO format) before storing and parse them back upon retrieval.
Always initialize `Cache` with `size_limit` (maximum cache size in bytes) and/or `cull_limit` (maximum items before culling). Regularly call `cache.cull()` if automatic culling isn't sufficient for your eviction policy.
Avoid placing DiskCache directories on NFS mounts if possible. If unavoidable, thoroughly test your application's concurrency under load and consider using a database-backed cache or a different caching solution for critical NFS-dependent workloads.
Switch to the default `pickle` serializer (remove `serializer=json_serializer` from `Cache` initialization), or convert your objects to a JSON-serializable format (e.g., dictionary, list, string) before storing them. For custom classes, you might need to implement a custom serializer/deserializer pair.
Ensure the user running the Python script has full read/write/execute permissions for the cache directory and its contents. This often occurs in containerized environments or on shared file systems. Change the cache directory to a user-writable location or adjust file system permissions.
Ensure the base directory for the cache exists and is writable before initializing `Cache`. DiskCache will create the actual cache subdirectories, but its base path must be valid. Verify no external process is inadvertently deleting the cache directory while your application is running.
No dependency data recorded yet.