Fcache: File-Based Cache
Fcache is a Python library that provides a dictionary-like, file-based cache module. It is designed to be simple to use, includes an optional write buffer, and is compatible with Python's `shelve` module. The current version is 0.6.0, and releases occur on an as-needed basis, with the last major update in late 2024.
Warnings
- gotcha Failing to call `FileCache.close()` can lead to data loss. Buffered writes to the file system may not be flushed, especially upon unexpected program termination.
- gotcha File-based caches, if not explicitly managed, can consume significant disk space over time. `fcache` does not automatically implement eviction policies like LRU or TTL out-of-the-box.
- breaking The `FileCache.delete()` method permanently removes the cache directory and all its contents from the file system. This operation is irreversible.
- gotcha While `fcache` leverages `shelve` for persistence, concurrent access from multiple processes or threads without proper synchronization mechanisms (not provided by `fcache` itself for all operations) could potentially lead to data corruption or race conditions, especially on write operations.
Install
-
pip install fcache
Imports
- FileCache
from fcache.cache import FileCache
Quickstart
from fcache.cache import FileCache
# Create a cache named 'myapp' in a default location
mycache = FileCache('myapp')
# Store data
mycache['greeting'] = 'Hello, Fcache!'
mycache['number'] = 123
# Retrieve data
print(f"Retrieved greeting: {mycache['greeting']}")
print(f"Retrieved number: {mycache['number']}")
# Check if a key exists
print(f"'greeting' in cache: {'greeting' in mycache}")
# Update data
mycache['greeting'] = 'Hola, Fcache!'
print(f"Updated greeting: {mycache['greeting']}")
# Close the cache to ensure data is flushed (important!)
mycache.close()
# Re-open and verify persistence
another_cache_instance = FileCache('myapp')
print(f"Re-opened greeting: {another_cache_instance['greeting']}")
another_cache_instance.close()