Skip to content

Commit

Permalink
Delete specific cache and check if cache exists
Browse files Browse the repository at this point in the history
  • Loading branch information
任鹏 committed Jun 26, 2024
1 parent 4f34937 commit 51acc88
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/persist_cache/caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,23 @@ def get(key: str, dir: str, expiry: Union[int, float, timedelta, None] = None) -
with open(path, 'rb') as file:
return deserialize(file.read())

def remove(key: str, dir: str) -> None:
"""Remove the given key of the provided cache to the specified value."""

path = f'{dir}/{key}.msgpack'

# Lock the entry before writing to it.
with FileLock(f'{path}.lock'):
if os.path.exists(path):
os.remove(path)

def exists(key: str, dir: str) -> bool:
"""Check if the given key exists in the provided cache."""

path = f'{dir}/{key}.msgpack'

return os.path.exists(path)

def hash(data: Any) -> str:
"""Hash the given data."""

Expand Down
26 changes: 26 additions & 0 deletions src/persist_cache/persist_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,11 +185,37 @@ def set_expiry(value: Union[int, float, timedelta, None]) -> None:

expiry = value

def delete_once(*args, **kwargs) -> None:
"""Remove the cache."""
nonlocal dir, expiry, is_method

# Map arguments to their keywords or the keyword of the args parameter where necessary, filtering out the first argument if the function is a method, to enable the consistent caching of function calls where positional arguments are used on some occasions and keyword arguments are used on others.
arguments = inflate_arguments(signature, args_parameter, args_i, args[is_method:], kwargs)

# Hash the arguments to produce the cache key.
key = caching.hash(arguments)

caching.remove(key, dir)

def exists(*args, **kwargs) -> None:
"""Check if cache exists"""
nonlocal dir, expiry, is_method

# Map arguments to their keywords or the keyword of the args parameter where necessary, filtering out the first argument if the function is a method, to enable the consistent caching of function calls where positional arguments are used on some occasions and keyword arguments are used on others.
arguments = inflate_arguments(signature, args_parameter, args_i, args[is_method:], kwargs)

# Hash the arguments to produce the cache key.
key = caching.hash(arguments)

return caching.exists(key, dir)

wrapper.delete_cache = delete_cache
wrapper.clear_cache = clear_cache
wrapper.cache_clear = wrapper.clear_cache # Add an alias for cache_clear which is used by lru_cache.
wrapper.flush_cache = flush_cache
wrapper.set_expiry = set_expiry
wrapper.delete_once = delete_once
wrapper.exists = exists

# Preserve the original function.
wrapper.__wrapped__ = func
Expand Down

0 comments on commit 51acc88

Please sign in to comment.