cachelib
Cachelib is a Python library that provides a collection of cache implementations sharing a common API interface, originally extracted from the Werkzeug project. It offers various backends like in-memory, file system, Redis, Memcached, DynamoDB, and MongoDB. The library is actively maintained by the Pallets organization, with several minor and patch releases occurring throughout the year.
Warnings
- breaking Python 3.7 support was dropped in Cachelib 0.11.0. Older versions (0.7.0) dropped Python 3.6 support. Ensure your Python environment is 3.8+.
- deprecated The methods `RedisCache.load_object` and `RedisCache.dump_object` were removed in Cachelib 0.8.0. These were internal methods and their direct use would have caused breaking changes.
- gotcha The `FileSystemCache` requires exclusive use of its `cache_dir` parameter. If other processes or manual interventions modify files within this directory, the cache may behave unexpectedly (e.g., deleting unintended files).
- gotcha In Cachelib 0.13.0, the `hashlib.md5` default for `FileSystemCache` was changed to be lazy-loaded. This was to prevent issues in FIPS-compliant environments where MD5 might not be available at import time. If you relied on `hashlib.md5` being available immediately at import, or if you need to specify a different hash method for FIPS compliance, consider this change.
- gotcha In `RedisCache` version 0.12.0, a fix was implemented to correctly handle a string for the `host` parameter, where previously passing a non-string 'host object' might have caused issues.
Install
-
pip install cachelib -
pip install cachelib[redis] -
pip install cachelib[memcached] -
pip install cachelib[dynamodb] -
pip install cachelib[mongodb]
Imports
- SimpleCache
from cachelib import SimpleCache
- FileSystemCache
from cachelib import FileSystemCache
- RedisCache
from cachelib import RedisCache
Quickstart
from cachelib import SimpleCache
# Initialize an in-memory cache
cache = SimpleCache(threshold=500, default_timeout=300)
# Set a value
cache.set("my_key", "my_value", timeout=60)
# Get a value
value = cache.get("my_key")
print(f"Retrieved: {value}")
# Check if a key exists
exists = cache.has("my_key")
print(f"Key 'my_key' exists: {exists}")
# Delete a key
cache.delete("my_key")
exists_after_delete = cache.has("my_key")
print(f"Key 'my_key' exists after delete: {exists_after_delete}")
# Example with FileSystemCache (requires a directory)
import os
import tempfile
with tempfile.TemporaryDirectory() as temp_dir:
file_cache = FileSystemCache(cache_dir=os.path.join(temp_dir, "cache"), threshold=100)
file_cache.set("file_key", "file_value", timeout=300)
file_value = file_cache.get("file_key")
print(f"Retrieved from file cache: {file_value}")
file_cache.clear() # Clean up temporary cache dir