Skip to main content

Basic Redis caching for functions

Project description

CI pypi license

python-redis-cache

Simple redis cache for Python functions

Requirements

  • Redis 5+
  • Python 3.8+ (should work in Python 3.6+, but not tested)

How to install

pip install python-redis-cache

How to use

from redis import StrictRedis
from redis_cache import RedisCache

client = StrictRedis(host="redis", decode_responses=True)
cache = RedisCache(redis_client=client)


@cache.cache()
def my_func(arg1, arg2):
    result = some_expensive_operation()
    return result

# Use the function
my_func(1, 2)

# Call it again with the same arguments and it will use cache
my_func(1, 2)

# Invalidate a single value
my_func.invalidate(1, 2)

# Invalidate all values for function
my_func.invalidate_all()

Limitations and things to know

Arguments and return types must be JSON serializable by default. You can override the serializer, but be careful with using Pickle. Make sure you understand the security risks. Pickle should not be used with untrusted values. https://security.stackexchange.com/questions/183966/safely-load-a-pickle-file decode_responses parameter must be False in redis client if you use pickle.

  • ttl - is based on the time from when it's first inserted in the cache, not based on the last access
  • limit - The limit will revoke keys (once it hits the limit) based on FIFO, not based on LRU

API

# Create the redis cache
cache = RedisCache(redis_client, prefix="rc", serializer=dumps, deserializer=loads, key_serializer=None, exception_handler=None)

# Cache decorator to go on functions, see above
cache.cache(ttl=..., limit=..., namespace=...) -> Callable[[Callable], Callable]

# Get multiple values from the cache
cache.mget([{"fn": my_func, "args": [1,2], "kwargs": {}}, ...]) -> List[Any]

Redis

# Cached function API

# Returns a cached value, if it exists in cache. Saves value in cache if it doesn't exist
cached_func(*args, *kwargs)

# Invalidates a single value
cached_func.invalidate(*args, **kwargs)

# Invalidates all values for cached function
cached_func.invalidate_all()
  • prefix - The string to prefix the redis keys with
  • serializer/deserializer - functions to convert arguments and return value to a string (user JSON by default)
  • ttl - The time in seconds to cache the return value
  • namespace - The string namespace of the cache. This is useful for allowing multiple functions to use the same cache. By default its f'{function.__module__}.{function.__file__}'
  • exception_handler - Function to handle Redis cache exceptions. This allows you to fall back to calling the original function or logging exceptions. Function has the following signature exception_handler(exception: Exception, function: Callable, args: List, kwargs: Dict) -> Any. If using this handler, reraise the exception in the handler to stop execution of the function. All return results will be used even if None. If handler not defined, it will raise the exception and not call the original function.

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

python-redis-cache-3.0.0.tar.gz (8.1 kB view details)

Uploaded Source

Built Distribution

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

python_redis_cache-3.0.0-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

File details

Details for the file python-redis-cache-3.0.0.tar.gz.

File metadata

  • Download URL: python-redis-cache-3.0.0.tar.gz
  • Upload date:
  • Size: 8.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.2 CPython/3.11.7

File hashes

Hashes for python-redis-cache-3.0.0.tar.gz
Algorithm Hash digest
SHA256 435c0efeba30e87a433476d89c7f9242a38271f553e3b1e1513a482dff64038a
MD5 c03e03a48d8cf58873d939d8c79f0934
BLAKE2b-256 86baf24f6dd837ffb3c246ab7508e2e7984bd4630cf8d7a273d35a78d4356ecf

See more details on using hashes here.

File details

Details for the file python_redis_cache-3.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for python_redis_cache-3.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0dd82408f5cbd13e4b04173ed61007181b7cb34133a807dcdebbcfb2bd0f064d
MD5 01100e7472a96f5005f1c13c8a7b53e3
BLAKE2b-256 f3f2ccc2d7e9fb43d2d4bb871b638d307b4822db8e9062ab0663547a06956d02

See more details on using hashes here.

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