Skip to content

Commit

Permalink
add support for sync non-fastapi functions
Browse files Browse the repository at this point in the history
  • Loading branch information
bkanuka committed Jun 2, 2022
1 parent d9fd634 commit 085f330
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions src/fastapi_redis_cache/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,25 +84,47 @@ async def inner_wrapper(*args, **kwargs):

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

func_kwargs = kwargs.copy()
redis_cache = FastApiRedisCache()
if redis_cache.not_connected:
# if the redis client is not connected or request is not cacheable, no caching behavior is performed.
return await get_api_response_async(func, *args, **kwargs)
return await func(*args, **kwargs)
key = redis_cache.get_cache_key(func, *args, **kwargs)
ttl, in_cache = redis_cache.check_cache(key)
if in_cache:
return deserialize_json(in_cache)

response_data = await get_api_response_async(func, *args, **kwargs)
response_data = await func(*args, **kwargs)
ttl = calculate_ttl(expire)
redis_cache.add_to_cache(key, response_data, ttl)
return response_data

return inner_wrapper
@wraps(func)
def inner_wrapper_sync(*args, **kwargs):
"""Return cached value if one exists, otherwise evaluate the wrapped function and cache the result."""

func_kwargs = kwargs.copy()
redis_cache = FastApiRedisCache()
if redis_cache.not_connected:
# if the redis client is not connected or request is not cacheable, no caching behavior is performed.
return func(*args, **kwargs)
key = redis_cache.get_cache_key(func, *args, **kwargs)
ttl, in_cache = redis_cache.check_cache(key)
if in_cache:
return deserialize_json(in_cache)

response_data = func(*args, **kwargs)
ttl = calculate_ttl(expire)
redis_cache.add_to_cache(key, response_data, ttl)
return response_data

if asyncio.iscoroutinefunction(func):
return inner_wrapper_async
else:
return inner_wrapper_sync

if fastapi_route:
return fastapi_route_wrapper
Expand Down

0 comments on commit 085f330

Please sign in to comment.