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

Simplify cache namespace and key encoding logic for v1 #670

Merged
merged 36 commits into from
Feb 27, 2023
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
7bd719a
Move namespace logic to BaseCache.build_key()
padraic-shafer Feb 18, 2023
0eeab3e
BaseCache._build_key() needs keyword param
padraic-shafer Feb 18, 2023
25943bd
ut/test_base/alt_base_cache tests use clearer default namespace
padraic-shafer Feb 19, 2023
fcd7afc
Update ut/test_base/alt_base_cache tests with new build_key() namespa…
padraic-shafer Feb 19, 2023
139e0a4
Update redis namespaced key for new build_key() compatibility
padraic-shafer Feb 19, 2023
eebe299
Update memcached key encoding for new build_key() compatibility
padraic-shafer Feb 19, 2023
6622f57
test/ut/test_base.py now calls build_key(), rather than _build_key()
padraic-shafer Feb 19, 2023
54ce48d
Move Enum _ensure_key() logic into BaseCache:build_key()
padraic-shafer Feb 19, 2023
b2e58d7
Update changelog with revisied cache build_key() scheme
padraic-shafer Feb 19, 2023
223b537
Clarify that output of BaseCache key_builder arg should be a string
padraic-shafer Feb 19, 2023
e8d6037
Clarify 'key_builder' parameter docstring in 'BaseCache.__init__()'
padraic-shafer Feb 20, 2023
9da3608
Merge branch 'master' into simplify-cache-namespace
padraic-shafer Feb 21, 2023
db94261
Ensure that cache namespace is a string
padraic-shafer Feb 21, 2023
84ce34c
mypy annotations for build_key() with namespace
padraic-shafer Feb 22, 2023
8392b15
Merge branch 'master' into simplify-cache-namespace
padraic-shafer Feb 22, 2023
16db995
Define BaseCache as generic, typed by backend cache key
padraic-shafer Feb 23, 2023
9dc7c77
Update tests for BaseCache with TypeVar
padraic-shafer Feb 24, 2023
a757e9a
Propagate type annotations for mypy compliance
padraic-shafer Feb 24, 2023
54093a1
Resolve mypy type annotations in tests
padraic-shafer Feb 24, 2023
d00a18b
Default namespace is empty string for decorators
padraic-shafer Feb 24, 2023
7239f16
Call build_key() with namespace as positional argument
padraic-shafer Feb 24, 2023
5995d64
redis.asyncio.Redis is generic for type checking purposes, but not at…
padraic-shafer Feb 24, 2023
e8c2306
Update alt_key_builder example with revised build_key() logickey_builder
padraic-shafer Feb 24, 2023
4126d60
Remove unneeded typing in decorator tests [mypy]
padraic-shafer Feb 24, 2023
3563def
BaseCache key_builder param defaults to lambda
padraic-shafer Feb 24, 2023
07e1919
Remove extraneous comments
padraic-shafer Feb 24, 2023
589d2b8
Remove bound on CacheKeyType
padraic-shafer Feb 24, 2023
08d8bf9
Correct the return annotation for redis_client fixture
padraic-shafer Feb 24, 2023
08b70d7
Test for abstract BaseCache
padraic-shafer Feb 24, 2023
64436a0
Revert extraneous mypy typing fixes
padraic-shafer Feb 24, 2023
bc385f7
Revise the changelog for PR #670
padraic-shafer Feb 24, 2023
396952f
Update redis.py
Dreamsorcerer Feb 27, 2023
6c4780e
Update base.py
Dreamsorcerer Feb 27, 2023
ce2f26a
Update alt_key_builder.py
Dreamsorcerer Feb 27, 2023
3d50611
Update CHANGES.rst
Dreamsorcerer Feb 27, 2023
23cd481
Update CHANGES.rst
Dreamsorcerer Feb 27, 2023
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
4 changes: 4 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ There are a number of backwards-incompatible changes. These points should help w
* The ``key`` parameter has been removed from the ``cached`` decorator. The behaviour can be easily reimplemented with ``key_builder=lambda *a, **kw: "foo"``
* When using the ``key_builder`` parameter in ``@multicached``, the function will now return the original, unmodified keys, only using the transformed keys in the cache (this has always been the documented behaviour, but not the implemented behaviour).
* ``BaseSerializer`` is now an ``ABC``, so cannot be instantiated directly.
* The logic for encoding a cache key and selecting the key's namespace is now encapsulated in
the ``build_key(key, namespace)`` member of BaseCache (and its backend subclasses). Now
creating a cache with a custom ``key_builder`` argument simply requires that function to
return any string mapping from the ``key`` and optional ``namespace`` parameters.


0.12.0 (2023-01-13)
Expand Down
4 changes: 2 additions & 2 deletions aiocache/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging
from typing import Dict, Type
from typing import Any, Dict, Type

from .backends.memory import SimpleMemoryCache
from .base import BaseCache
Expand All @@ -8,7 +8,7 @@

logger = logging.getLogger(__name__)

AIOCACHE_CACHES: Dict[str, Type[BaseCache]] = {SimpleMemoryCache.NAME: SimpleMemoryCache}
AIOCACHE_CACHES: Dict[str, Type[BaseCache[Any]]] = {SimpleMemoryCache.NAME: SimpleMemoryCache}

try:
import redis
Expand Down
10 changes: 6 additions & 4 deletions aiocache/backends/memcached.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import asyncio
from typing import Optional

import aiomcache

from aiocache.base import BaseCache
from aiocache.serializers import JsonSerializer


class MemcachedBackend(BaseCache):
class MemcachedBackend(BaseCache[bytes]):
def __init__(self, endpoint="127.0.0.1", port=11211, pool_size=2, **kwargs):
super().__init__(**kwargs)
self.endpoint = endpoint
Expand Down Expand Up @@ -119,6 +120,7 @@ async def _close(self, *args, _conn=None, **kwargs):
await self.client.close()


# class MemcachedCache(MemcachedBackend):
padraic-shafer marked this conversation as resolved.
Show resolved Hide resolved
class MemcachedCache(MemcachedBackend):
"""
Memcached cache implementation with the following components as defaults:
Expand All @@ -130,7 +132,7 @@ class MemcachedCache(MemcachedBackend):
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None
the backend. Default is an empty string, "".
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5.
:param endpoint: str with the endpoint to connect to. Default is 127.0.0.1.
Expand All @@ -147,8 +149,8 @@ def __init__(self, serializer=None, **kwargs):
def parse_uri_path(cls, path):
return {}

def _build_key(self, key, namespace=None):
ns_key = super()._build_key(key, namespace=namespace).replace(" ", "_")
def build_key(self, key: str, namespace: Optional[str] = None) -> bytes:
ns_key = self._str_build_key(key, namespace).replace(" ", "_")
return str.encode(ns_key)

def __repr__(self): # pragma: no cover
Expand Down
13 changes: 10 additions & 3 deletions aiocache/backends/memory.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
import asyncio
from typing import Dict
from typing import Dict, Optional

from aiocache.base import BaseCache
from aiocache.serializers import NullSerializer


class SimpleMemoryBackend(BaseCache):
class SimpleMemoryBackend(BaseCache[str]):
"""
Wrapper around dict operations to use it as a cache backend
"""

def __init__(self, **kwargs):
super().__init__(**kwargs)
# Assigning build_key here is clear and avoids the extra stack frame
# from nesting the call to _str_build_key() in an override of build_key()
# ...but mypy needs the override definition to recognize a concrete class
# self.build_key = self._str_build_key # Simple, but not mypy-friendly
padraic-shafer marked this conversation as resolved.
Show resolved Hide resolved

self._cache: Dict[str, object] = {}
self._handlers: Dict[str, asyncio.TimerHandle] = {}
Expand Down Expand Up @@ -118,7 +122,7 @@ class SimpleMemoryCache(SimpleMemoryBackend):
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None.
the backend. Default is an empty string, "".
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5.
"""
Expand All @@ -131,3 +135,6 @@ def __init__(self, serializer=None, **kwargs):
@classmethod
def parse_uri_path(cls, path):
return {}

def build_key(self, key: str, namespace: Optional[str] = None) -> str:
return self._str_build_key(key, namespace)
Dreamsorcerer marked this conversation as resolved.
Show resolved Hide resolved
42 changes: 28 additions & 14 deletions aiocache/backends/redis.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import itertools
import warnings
from typing import Any, Callable, Optional, TYPE_CHECKING

import redis.asyncio as redis
from redis.exceptions import ResponseError as IncrbyException

from aiocache.base import BaseCache, _ensure_key
if TYPE_CHECKING:
from aiocache.serializers import BaseSerializer
from aiocache.base import BaseCache
from aiocache.serializers import JsonSerializer


_NOT_SET = object()


class RedisBackend(BaseCache):
class RedisBackend(BaseCache[str]):
RELEASE_SCRIPT = (
"if redis.call('get',KEYS[1]) == ARGV[1] then"
" return redis.call('del',KEYS[1])"
Expand Down Expand Up @@ -44,6 +47,10 @@ def __init__(
**kwargs,
):
super().__init__(**kwargs)
# Assigning build_key here is clear and avoids the extra stack frame
# from nesting the call to _str_build_key() in an override of build_key()
# ...but mypy needs the override definition to recognize a concrete class
# self.build_key = self._str_build_key # Simple, but not mypy-friendly
if pool_min_size is not _NOT_SET:
warnings.warn(
"Parameter 'pool_min_size' is deprecated since aiocache 0.12",
Expand Down Expand Up @@ -186,7 +193,7 @@ class RedisCache(RedisBackend):
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None.
the backend. Default is an empty string, "".
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5.
:param endpoint: str with the endpoint to connect to. Default is "127.0.0.1".
Expand All @@ -199,8 +206,21 @@ class RedisCache(RedisBackend):

NAME = "redis"

def __init__(self, serializer=None, **kwargs):
super().__init__(serializer=serializer or JsonSerializer(), **kwargs)
def __init__(
self,
serializer: "Optional[BaseSerializer]" = None,
namespace: str = "",
key_builder: Optional[Callable[[str, str], str]] = None,
**kwargs: Any,
):
super().__init__(
serializer=serializer or JsonSerializer(),
namespace=namespace,
key_builder=key_builder or (
lambda key, namespace: f"{namespace}:{key}" if namespace else key
),
**kwargs,
)

@classmethod
def parse_uri_path(cls, path):
Expand All @@ -218,14 +238,8 @@ def parse_uri_path(cls, path):
options["db"] = db
return options

def _build_key(self, key, namespace=None):
if namespace is not None:
return "{}{}{}".format(
namespace, ":" if namespace else "", _ensure_key(key))
if self.namespace is not None:
return "{}{}{}".format(
self.namespace, ":" if self.namespace else "", _ensure_key(key))
return key

def __repr__(self): # pragma: no cover
return "RedisCache ({}:{})".format(self.endpoint, self.port)

def build_key(self, key: str, namespace: Optional[str] = None) -> str:
return self._str_build_key(key, namespace)
Loading