Skip to content

Commit

Permalink
allow use_cache=False and return_cache_entry=True (#111)
Browse files Browse the repository at this point in the history
  • Loading branch information
malmans2 authored Feb 1, 2024
1 parent f1a03a1 commit 77165b3
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 37 deletions.
41 changes: 21 additions & 20 deletions cacholote/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def cacheable(func: F) -> F:
def wrapper(*args: Any, **kwargs: Any) -> Any:
settings = config.get()

if not settings.use_cache:
if not settings.use_cache and not settings.return_cache_entry:
return func(*args, **kwargs)

try:
Expand All @@ -62,25 +62,26 @@ def wrapper(*args: Any, **kwargs: Any) -> Any:
warnings.warn(f"can NOT encode python call: {ex!r}", UserWarning)
return func(*args, **kwargs)

filters = [
database.CacheEntry.key == hexdigest,
database.CacheEntry.expiration > utils.utcnow(),
]
if settings.expiration:
# When expiration is provided, only get entries with matching expiration
filters.append(database.CacheEntry.expiration == settings.expiration)

with settings.sessionmaker() as session:
for cache_entry in session.scalars(
sa.select(database.CacheEntry)
.filter(*filters)
.order_by(database.CacheEntry.timestamp.desc())
):
try:
return _decode_and_update(session, cache_entry, settings)
except decode.DecodeError as ex:
warnings.warn(str(ex), UserWarning)
clean._delete_cache_entry(session, cache_entry)
if settings.use_cache:
filters = [
database.CacheEntry.key == hexdigest,
database.CacheEntry.expiration > utils.utcnow(),
]
if settings.expiration:
# When expiration is provided, only get entries with matching expiration
filters.append(database.CacheEntry.expiration == settings.expiration)

with settings.sessionmaker() as session:
for cache_entry in session.scalars(
sa.select(database.CacheEntry)
.filter(*filters)
.order_by(database.CacheEntry.timestamp.desc())
):
try:
return _decode_and_update(session, cache_entry, settings)
except decode.DecodeError as ex:
warnings.warn(str(ex), UserWarning)
clean._delete_cache_entry(session, cache_entry)

result = func(*args, **kwargs)
cache_entry = database.CacheEntry(
Expand Down
12 changes: 0 additions & 12 deletions cacholote/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,18 +72,6 @@ def validate_create_engine_kwargs(
create_engine_kwargs["poolclass"] = getattr(sa.pool, poolclass)
return create_engine_kwargs

@pydantic.field_validator("return_cache_entry")
def validate_return_cache_entry(
cls: pydantic_settings.BaseSettings,
return_cache_entry: bool,
info: pydantic.ValidationInfo,
) -> bool:
if return_cache_entry is True and info.data["use_cache"] is False:
raise ValueError(
"`use_cache` must be True when `return_cache_entry` is True"
)
return return_cache_entry

@pydantic.field_validator("expiration")
def validate_expiration(
cls: pydantic_settings.BaseSettings, expiration: Optional[datetime.datetime]
Expand Down
18 changes: 13 additions & 5 deletions tests/test_30_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,13 +109,21 @@ def test_same_args_kwargs() -> None:


@pytest.mark.parametrize("use_cache", [True, False])
def test_use_cache(use_cache: bool) -> None:
config.set(use_cache=use_cache)
@pytest.mark.parametrize("return_cache_entry", [True, False])
def test_use_cache(use_cache: bool, return_cache_entry: bool) -> None:
config.set(use_cache=use_cache, return_cache_entry=return_cache_entry)

if use_cache:
assert cached_now() == cached_now()
first = cached_now()
second = cached_now()

if return_cache_entry:
assert isinstance(first, database.CacheEntry)
assert isinstance(second, database.CacheEntry)
assert first.id == second.id if use_cache else first.id != second.id
else:
assert cached_now() < cached_now()
assert isinstance(first, datetime.datetime)
assert isinstance(second, datetime.datetime)
assert first == second if use_cache else first != second


def test_expiration_and_return_cache_entry() -> None:
Expand Down

0 comments on commit 77165b3

Please sign in to comment.