Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add cache async support #4

Merged
merged 2 commits into from
Aug 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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