Skip to content

Commit

Permalink
Merge pull request #4 from GigantPro/AddAsyncSupport
Browse files Browse the repository at this point in the history
Add  cache async support
  • Loading branch information
GigantPro committed Aug 30, 2023
2 parents 1999f49 + 0e3cdfa commit 28b6ed7
Show file tree
Hide file tree
Showing 4 changed files with 98 additions and 56 deletions.
33 changes: 30 additions & 3 deletions frozenclass/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,21 @@

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.
:param ttl: Time-To-Live of cached valume, defaults to time(minute=10)
:type ttl: time | None, optional
:param is_async: Set True if decorated func is async, defaults to False
:type is_async: bool, optional
:return: Decorated func
:rtype: Callable
"""
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 @@ -39,5 +41,30 @@ def cached_func_without_time(*args, **kwargs) -> Any:
return result


return cached_func_with_time if ttl else cached_func_without_time
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
return async_cached_func_with_time if ttl else async_cached_func_without_time

return wrapper_func
Loading

0 comments on commit 28b6ed7

Please sign in to comment.