Skip to content

Commit

Permalink
Add async support
Browse files Browse the repository at this point in the history
  • Loading branch information
GigantPro committed Aug 30, 2023
1 parent 1999f49 commit 8bea55a
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 56 deletions.
33 changes: 30 additions & 3 deletions frozenclass/cache.py
Expand Up @@ -4,7 +4,8 @@

class CacheController:
"""The main class of the cache logic. Includes all caches logic"""
def cache(*, ttl: Optional[time] = time(minute=10)) -> Callable: # ( TTL_end, result )
def cache(*, ttl: Optional[time] = time(minute=10),
is_async: bool = False) -> Callable: # ( TTL_end, result )
"""Function-decorate for runtime caching.
The cache can either be overwritten or remain until the program terminates.
Expand All @@ -16,7 +17,6 @@ def cache(*, ttl: Optional[time] = time(minute=10)) -> Callable: # ( TTL_end, r
def wrapper_func(target_func: Callable) -> Callable:
__cached_vals = {}


def cached_func_with_time(*args, **kwargs) -> Any:
cached_ = __cached_vals.get((*args, *kwargs), None)
if cached_ and cached_[0] > datetime.now():
Expand All @@ -37,7 +37,34 @@ def cached_func_without_time(*args, **kwargs) -> Any:
result = target_func(*args, **kwargs)
__cached_vals[(*args, *kwargs)] = result
return result


async def async_cached_func_with_time(*args, **kwargs) -> Any:
cached_ = __cached_vals.get((*args, *kwargs), None)
if cached_ and cached_[0] > datetime.now():
return cached_[1]

result = await target_func(*args, **kwargs)

__cached_vals[(*args, *kwargs)] = \
(datetime.now() + timedelta(hours=ttl.hour, minutes=ttl.minute, seconds=ttl.second), result)

return result


async def async_cached_func_without_time(*args, **kwargs) -> Any:
try:
return __cached_vals[(*args, *kwargs)]
except KeyError:
result = await target_func(*args, **kwargs)
__cached_vals[(*args, *kwargs)] = result
return result


if not is_async:
return cached_func_with_time if ttl else cached_func_without_time

else:
return async_cached_func_with_time if ttl else async_cached_func_without_time

return cached_func_with_time if ttl else cached_func_without_time
return wrapper_func

0 comments on commit 8bea55a

Please sign in to comment.