cachelib

0.13.0 · active · verified Sun Apr 05

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a `SimpleCache` (in-memory) and a `FileSystemCache` (file-based) to store, retrieve, check for existence, and delete cached values. It highlights basic `set`, `get`, `has`, and `delete` operations. For `FileSystemCache`, a temporary directory is used for demonstration purposes.

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

view raw JSON →