Skip to main content

A simple cache library with sync/async support, Memory and Redis backend

Project description

Python Cachify Library

A simple and robust caching library for Python functions, supporting both synchronous and asynchronous code.

Features

  • Cache function results based on function ID and arguments
  • Supports both synchronous and asynchronous functions
  • Thread-safe locking to prevent duplicate cached function calls
  • Configurable Time-To-Live (TTL) for cached items
  • "Never Die" mode for functions that should keep cache refreshed automatically
  • Skip cache functionality to force fresh function execution while updating cache
  • Redis cache for distributed caching across multiple processes/machines

Installation

# Clone the repository
git clone https://github.com/PulsarDefi/cachify.git
cd cachify

# Install the package
poetry install

Usage

Basic Usage

from cachify import cache

# Cache function in sync functions
@cache(ttl=60) # ttl in seconds
def expensive_calculation(a, b):
    # Some expensive operation
    return a + b

# And async functions
@cache(ttl=3600) # ttl in seconds
async def another_calculation(url):
    # Some expensive IO call
    return await httpx.get(url).json()

Redis Cache

For distributed caching across multiple processes or machines, use rcache:

import redis
from cachify import setup_redis_config, rcache

# Configure Redis (call once at startup)
setup_redis_config(
    sync_client=redis.from_url("redis://localhost:6379/0"),
    key_prefix="myapp",       # default: "key_prefix", prefix searchable on redis "PREFIX:*"
    lock_timeout=10,          # default: 10, maximum lock lifetime in seconds
    on_error="silent",        # "silent" (default) or "raise" in case of redis errors
)

@rcache(ttl=300)
def get_user(user_id: int) -> dict:
    return fetch_from_database(user_id)

# Async version
import redis.asyncio as aredis

setup_redis_config(async_client=aredis.from_url("redis://localhost:6379/0"))

@rcache(ttl=300)
def get_user_async(user_id: int) -> dict:
    return await fetch_from_database(user_id)

Never Die Cache

The never_die feature ensures that cached values never expire by automatically refreshing them in the background:

# Cache with never_die (automatic refresh)
@cache(ttl=300, never_die=True)
def critical_operation(data_id: str):
    # Expensive operation that should always be available from cache
    return fetch_data_from_database(data_id)

How Never Die Works:

  1. When a function with never_die=True is first called, the result is cached
  2. A background thread monitors all never_die functions
  3. On cache expiration (TTL), the function is automatically called again
  4. The cache is updated with the new result
  5. If the refresh operation fails, the existing cached value is preserved
  6. Clients always get fast response times by reading from cache

Benefits:

  • Cache is always "warm" and ready to serve
  • No user request ever has to wait for the expensive operation
  • If a dependency service from the cached function goes down temporarily, the last successful result is still available
  • Perfect for critical operations where latency must be minimized

Skip Cache

The skip_cache feature allows you to bypass reading from cache while still updating it with fresh results:

@cache(ttl=300)
def get_user_data(user_id):
    # Expensive operation to fetch user data
    return fetch_from_database(user_id)

# Normal call - uses cache if available
user = get_user_data(123)
# Force fresh execution while updating cache
fresh_user = get_user_data(123, skip_cache=True)
# Next normal call will get the updated cached value
updated_user = get_user_data(123)

How Skip Cache Works:

  1. When skip_cache=True is passed, the function bypasses reading from cache
  2. The function executes normally and returns fresh results
  3. The fresh result is stored in the cache, updating any existing cached value
  4. Subsequent calls without skip_cache=True will use the updated cached value
  5. The TTL timer resets from when the cache last was updated

Benefits:

  • Force refresh of potentially stale data while keeping cache warm
  • Ensuring fresh data for critical operations while maintaining cache for other calls

Testing

Run the test scripts

poetry run python -m pytest

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cachify-0.2.0.tar.gz (13.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cachify-0.2.0-py3-none-any.whl (18.8 kB view details)

Uploaded Python 3

File details

Details for the file cachify-0.2.0.tar.gz.

File metadata

  • Download URL: cachify-0.2.0.tar.gz
  • Upload date:
  • Size: 13.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for cachify-0.2.0.tar.gz
Algorithm Hash digest
SHA256 de4e83981d891cf1477a2a17f8e3f307567da0f4e110784290926e21d3f8c9d6
MD5 81087e5092be871acf8790d6efe748ce
BLAKE2b-256 636db55c9be4731cea3bb76a9d9ad9a2d39ddf40d53e6cc9dd991caca09b9542

See more details on using hashes here.

Provenance

The following attestation bundles were made for cachify-0.2.0.tar.gz:

Publisher: publish.yml on PulsarDataSolutions/cachify

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file cachify-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: cachify-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 18.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for cachify-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f098e8be04d867ec3cf0aa1dedd60524b20bb1baed168e3ad72fd51e19abe3f3
MD5 0dd4fa4b58b82066cefb4cfedada53b2
BLAKE2b-256 506f37cdf910dee3b2f07bf31d389b3d629e572f979a9deb1b39a3a022ba0fde

See more details on using hashes here.

Provenance

The following attestation bundles were made for cachify-0.2.0-py3-none-any.whl:

Publisher: publish.yml on PulsarDataSolutions/cachify

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page