Skip to content
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
17 changes: 10 additions & 7 deletions cashews/key_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
from typing import Any

_REWRITE = "__rewrite"
_template_context: ContextVar[dict[str, Any]] = ContextVar("template_context")
_template_context.set({_REWRITE: False})
TContext = dict[str, Any]
_template_context: ContextVar[TContext | None] = ContextVar("template_context", default=None)
_empty = object()


Expand All @@ -22,25 +22,28 @@ def context(rewrite=_empty, **values) -> Iterator[None]:
)
else:
rewrite = False
new_context = {**_template_context.get(), **values}
new_context[_REWRITE] = rewrite
new_context = {**_get_raw(), **values, _REWRITE: rewrite}
token = _template_context.set(new_context)
try:
yield
finally:
_template_context.reset(token)


def get() -> tuple[dict[str, Any], bool]:
_context = {**_template_context.get()}
def get() -> tuple[TContext, bool]:
_context = {**_get_raw()} # a copy
return _context, _context.pop(_REWRITE)


def _get_raw() -> TContext:
return _template_context.get() or {_REWRITE: False}


def register(*names: str) -> None:
warnings.warn(
"`register_key_context` deprecated and will be removed in next release, use @ notation",
DeprecationWarning,
stacklevel=2,
)
new_names = dict.fromkeys(names, "")
_template_context.set({**new_names, **_template_context.get()})
_template_context.set({**new_names, **_get_raw()})
17 changes: 17 additions & 0 deletions tests/test_bugs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import asyncio

from cashews import Cache


async def test_issue_382():
cache = Cache()
cache.setup("mem://")

@cache(ttl=60, key="item:{item_id}")
async def get_item(item_id: int):
return f"item_{item_id}"

def sync_get_item(item_id: int):
return asyncio.run(get_item(item_id))

await asyncio.get_running_loop().run_in_executor(None, sync_get_item, 123)
Loading