Skip to content

Commit 085f330

Browse files
author
Bennett Kanuka
committed
add support for sync non-fastapi functions
1 parent d9fd634 commit 085f330

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

src/fastapi_redis_cache/cache.py

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,25 +84,47 @@ async def inner_wrapper(*args, **kwargs):
8484

8585
def standard_wrapper(func):
8686
@wraps(func)
87-
async def inner_wrapper(*args, **kwargs):
87+
async def inner_wrapper_async(*args, **kwargs):
8888
"""Return cached value if one exists, otherwise evaluate the wrapped function and cache the result."""
8989

9090
func_kwargs = kwargs.copy()
9191
redis_cache = FastApiRedisCache()
9292
if redis_cache.not_connected:
9393
# if the redis client is not connected or request is not cacheable, no caching behavior is performed.
94-
return await get_api_response_async(func, *args, **kwargs)
94+
return await func(*args, **kwargs)
9595
key = redis_cache.get_cache_key(func, *args, **kwargs)
9696
ttl, in_cache = redis_cache.check_cache(key)
9797
if in_cache:
9898
return deserialize_json(in_cache)
9999

100-
response_data = await get_api_response_async(func, *args, **kwargs)
100+
response_data = await func(*args, **kwargs)
101101
ttl = calculate_ttl(expire)
102102
redis_cache.add_to_cache(key, response_data, ttl)
103103
return response_data
104104

105-
return inner_wrapper
105+
@wraps(func)
106+
def inner_wrapper_sync(*args, **kwargs):
107+
"""Return cached value if one exists, otherwise evaluate the wrapped function and cache the result."""
108+
109+
func_kwargs = kwargs.copy()
110+
redis_cache = FastApiRedisCache()
111+
if redis_cache.not_connected:
112+
# if the redis client is not connected or request is not cacheable, no caching behavior is performed.
113+
return func(*args, **kwargs)
114+
key = redis_cache.get_cache_key(func, *args, **kwargs)
115+
ttl, in_cache = redis_cache.check_cache(key)
116+
if in_cache:
117+
return deserialize_json(in_cache)
118+
119+
response_data = func(*args, **kwargs)
120+
ttl = calculate_ttl(expire)
121+
redis_cache.add_to_cache(key, response_data, ttl)
122+
return response_data
123+
124+
if asyncio.iscoroutinefunction(func):
125+
return inner_wrapper_async
126+
else:
127+
return inner_wrapper_sync
106128

107129
if fastapi_route:
108130
return fastapi_route_wrapper

0 commit comments

Comments
 (0)