DiskCache

5.6.3 · active · verified Sat Mar 28

DiskCache is an Apache2 licensed disk and file backed cache library, written in pure-Python, and compatible with Django. It provides a dictionary-like interface for persistent caching, leveraging SQLite for storage. The current version is 5.6.3, and it follows a major.minor.micro versioning scheme, with major versions intended for significant new features and potential breaking changes, though not always guaranteed.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the basic usage of `diskcache.Cache`, including setting and getting values, using expiration, checking key existence, and deleting items. It also shows the important step of closing the cache and cleaning up the cache directory for a runnable example.

import os
from diskcache import Cache

# Create a cache in a local directory (will be created if it doesn't exist)
# For production, specify a persistent path; for examples, a temporary path is fine.
cache_dir = os.path.join(os.getcwd(), 'my_diskcache_data')
cache = Cache(cache_dir)

try:
    # Set items in the cache
    cache['my_key'] = 'Hello, DiskCache!'
    cache.set('another_key', {'data': [1, 2, 3]}, expire=300) # expires in 5 minutes

    # Retrieve items from the cache
    value1 = cache['my_key']
    value2 = cache.get('another_key')
    value3 = cache.get('non_existent_key', 'default_value') # with a default

    print(f"Value for 'my_key': {value1}")
    print(f"Value for 'another_key': {value2}")
    print(f"Value for 'non_existent_key': {value3}")

    # Check if a key exists
    if 'my_key' in cache:
        print("'my_key' is in the cache.")

    # Delete an item
    del cache['my_key']
    print(f"'my_key' after deletion: {cache.get('my_key', 'DELETED')}")

finally:
    # It's crucial to close the cache for proper shutdown and resource release.
    cache.close()
    # For examples, clean up the created directory. In production, you would not typically delete it.
    if os.path.exists(cache_dir):
        import shutil
        shutil.rmtree(cache_dir)
        print(f"Cleaned up cache directory: {cache_dir}")

view raw JSON →