python-redis-cache icon indicating copy to clipboard operation
python-redis-cache copied to clipboard

Exception Handler is not working

Open waltzforvenus opened this issue 10 months ago • 0 comments

Code for replication:

(Testing using a redis instance with 10mb memory limit)


from typing import Any, Callable, Dict, List
import redis
from os import environ
from redis_cache import RedisCache
import logging


redis_host = environ.get('REDIS_HOST')
redis_port = environ.get('REDIS_PORT')
redis_username = environ.get('REDIS_USERNAME')
redis_password = environ.get('REDIS_PASSWORD')
deployment = environ.get('DEPLOY_ENV')


r = redis.StrictRedis(
    host=redis_host,
    port=redis_port,
    username=redis_username,
    password=redis_password,
    decode_responses=True
)


def exception_handler(exception: Exception, function: Callable, args: List, kwargs: Dict) -> Any:

    logging.error(
        f"Redis exception {exception} occurred in function {function.__name__} with args {args} and kwargs {kwargs}")
    return function(*args, **kwargs)


cache = RedisCache(redis_client=r, prefix=deployment,
                   exception_handler=exception_handler)


@cache.cache(ttl=60, limit=100, namespace='my_func_e', exception_handler=exception_handler)
def my_func(arg1, arg2):
    # generate a massive list
    return [i for i in range(10000000)]


my_func(1, 2)

my_func(1, 2)

print(my_func(1, 2))

Current Behavior:

Exception Raised with:
  File "/workspaces/**/redis_test.py", line 41, in <module>
      my_func(1, 2)
  redis.exceptions.OutOfMemoryError: command not allowed when used memory > 'maxmemory'. script: 89fe7989fd48f14708d9a9262248ca49158b7cec, on @user_script:5.

Expected Behavior: Exception handler is called and the exception is handled using the function

Probable Solution: Exception handler to be called when trying to upload to cache as well as it only gets called when trying to get data from the cache as I couldn't see that in the source code

waltzforvenus avatar Mar 04 '25 11:03 waltzforvenus