simple-redis-cache 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- __init__.py +0 -0
- simple_redis_cache/__init__.py +0 -0
- simple_redis_cache/cache.py +146 -0
- simple_redis_cache/encoder.py +17 -0
- simple_redis_cache/key_generator.py +45 -0
- simple_redis_cache-0.1.0.dist-info/METADATA +63 -0
- simple_redis_cache-0.1.0.dist-info/RECORD +10 -0
- simple_redis_cache-0.1.0.dist-info/WHEEL +5 -0
- simple_redis_cache-0.1.0.dist-info/licenses/LICENSE +21 -0
- simple_redis_cache-0.1.0.dist-info/top_level.txt +2 -0
__init__.py
ADDED
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from functools import wraps
|
|
3
|
+
import hashlib
|
|
4
|
+
import inspect
|
|
5
|
+
import json
|
|
6
|
+
from logging import Logger, getLogger
|
|
7
|
+
from typing import Callable, TypeVar, ParamSpec, cast
|
|
8
|
+
|
|
9
|
+
from redis.asyncio import Redis
|
|
10
|
+
|
|
11
|
+
from src.simple_redis_cache.encoder import CustomJSONEncoder
|
|
12
|
+
from src.simple_redis_cache.key_generator import clean_args
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
T = TypeVar("T")
|
|
16
|
+
P = ParamSpec("P")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Cache:
|
|
20
|
+
__slots__ = ("redis_client", "logger")
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self, redis_client: Redis, logger: Logger = getLogger(__name__)
|
|
24
|
+
) -> None:
|
|
25
|
+
self.redis_client = redis_client
|
|
26
|
+
self.logger = logger
|
|
27
|
+
|
|
28
|
+
def _gen_cache_key(
|
|
29
|
+
self,
|
|
30
|
+
func: Callable,
|
|
31
|
+
args: tuple,
|
|
32
|
+
kwargs: dict,
|
|
33
|
+
prefix: str | None = None,
|
|
34
|
+
) -> str:
|
|
35
|
+
cleaned_args = clean_args(args, func)
|
|
36
|
+
sorted_kwargs = dict(sorted(kwargs.items()))
|
|
37
|
+
|
|
38
|
+
data = {
|
|
39
|
+
"func_name": func.__name__,
|
|
40
|
+
"args": cleaned_args,
|
|
41
|
+
"kwargs": sorted_kwargs,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
key_hash = hashlib.sha256(
|
|
45
|
+
json.dumps(data, cls=CustomJSONEncoder, sort_keys=True).encode()
|
|
46
|
+
).hexdigest()
|
|
47
|
+
|
|
48
|
+
base_key = f"cache:{key_hash}"
|
|
49
|
+
if prefix:
|
|
50
|
+
return f"cache:{prefix}:{key_hash}"
|
|
51
|
+
return base_key
|
|
52
|
+
|
|
53
|
+
def cache(
|
|
54
|
+
self, ttl: int, prefix: str | None = None
|
|
55
|
+
) -> Callable[[Callable[P, T]], Callable[P, T]]:
|
|
56
|
+
def wrapper(func: Callable[P, T]) -> Callable[P, T]:
|
|
57
|
+
if not inspect.iscoroutinefunction(func):
|
|
58
|
+
raise TypeError(
|
|
59
|
+
f"@cache can only be used on async functions. "
|
|
60
|
+
f"'{func.__name__}' is sync."
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
@wraps(func)
|
|
64
|
+
async def inner(*args: P.args, **kwargs: P.kwargs) -> T:
|
|
65
|
+
cache_key = self._gen_cache_key(func, args, kwargs, prefix)
|
|
66
|
+
|
|
67
|
+
try:
|
|
68
|
+
cached = await self.redis_client.get(cache_key)
|
|
69
|
+
if cached:
|
|
70
|
+
self.logger.debug("Cache HIT: %s", cache_key)
|
|
71
|
+
if cached == "__NULL__":
|
|
72
|
+
return None # type: ignore # pragma: no cover
|
|
73
|
+
return json.loads(cached)
|
|
74
|
+
except Exception as exc:
|
|
75
|
+
self.logger.warning(
|
|
76
|
+
"Failed cache get for key: %s",
|
|
77
|
+
cache_key,
|
|
78
|
+
exc_info=exc,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
result = await func(*args, **kwargs)
|
|
82
|
+
|
|
83
|
+
try:
|
|
84
|
+
if result is None:
|
|
85
|
+
data_to_cache = "__NULL__"
|
|
86
|
+
else:
|
|
87
|
+
data_to_cache = json.dumps(result, cls=CustomJSONEncoder)
|
|
88
|
+
await self.redis_client.set(cache_key, data_to_cache, ex=ttl)
|
|
89
|
+
self.logger.debug("Cache saved: %s", cache_key)
|
|
90
|
+
except Exception as exc: # pragma: no cover
|
|
91
|
+
self.logger.warning(
|
|
92
|
+
"Failed cache set for key: %s",
|
|
93
|
+
cache_key,
|
|
94
|
+
exc_info=exc,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
return result
|
|
98
|
+
|
|
99
|
+
return cast(Callable[P, T], inner)
|
|
100
|
+
|
|
101
|
+
return wrapper
|
|
102
|
+
|
|
103
|
+
async def invalidate_cache(
|
|
104
|
+
self, prefix: str = "*", timeout_seconds: int = 30
|
|
105
|
+
) -> int:
|
|
106
|
+
if prefix == "*":
|
|
107
|
+
pattern = "cache:*"
|
|
108
|
+
else:
|
|
109
|
+
pattern = f"cache:{prefix}:*"
|
|
110
|
+
|
|
111
|
+
self.logger.debug("Starting cache invalidation by pattern: %s", pattern)
|
|
112
|
+
|
|
113
|
+
deleted_count = 0
|
|
114
|
+
cursor = 0
|
|
115
|
+
start_time = asyncio.get_event_loop().time()
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
while True:
|
|
119
|
+
if asyncio.get_event_loop().time() - start_time > timeout_seconds: # pragma: no cover
|
|
120
|
+
self.logger.warning(
|
|
121
|
+
"Cache invalidation timed out (%s)", timeout_seconds
|
|
122
|
+
)
|
|
123
|
+
break
|
|
124
|
+
|
|
125
|
+
cursor, keys = await self.redis_client.scan(
|
|
126
|
+
cursor,
|
|
127
|
+
match=pattern,
|
|
128
|
+
count=100,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
if keys:
|
|
132
|
+
await self.redis_client.delete(*keys)
|
|
133
|
+
deleted_count += len(keys)
|
|
134
|
+
|
|
135
|
+
if cursor == 0:
|
|
136
|
+
break
|
|
137
|
+
|
|
138
|
+
self.logger.info("Cache invalidated (%s keys)", deleted_count)
|
|
139
|
+
return deleted_count
|
|
140
|
+
|
|
141
|
+
except Exception as exc: # pragma: no cover
|
|
142
|
+
self.logger.error(
|
|
143
|
+
"Failed to invalidate cache",
|
|
144
|
+
exc_info=exc,
|
|
145
|
+
)
|
|
146
|
+
return deleted_count
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from decimal import Decimal
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class CustomJSONEncoder(json.JSONEncoder):
|
|
8
|
+
def default(self, obj: Any) -> Any:
|
|
9
|
+
if isinstance(obj, datetime):
|
|
10
|
+
return obj.isoformat()
|
|
11
|
+
if hasattr(obj, "model_dump"):
|
|
12
|
+
return obj.model_dump()
|
|
13
|
+
if hasattr(obj, "hex"):
|
|
14
|
+
return str(obj)
|
|
15
|
+
if isinstance(obj, Decimal):
|
|
16
|
+
return float(obj)
|
|
17
|
+
return super().default(obj)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import inspect
|
|
3
|
+
import json
|
|
4
|
+
from typing import Callable
|
|
5
|
+
|
|
6
|
+
from src.simple_redis_cache.encoder import CustomJSONEncoder
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def clean_args(args: tuple, func: Callable) -> tuple:
|
|
10
|
+
"""Remove 'self/cls/mcs' from args"""
|
|
11
|
+
if not args:
|
|
12
|
+
return args
|
|
13
|
+
|
|
14
|
+
sig = inspect.signature(func)
|
|
15
|
+
params = list(sig.parameters.keys())
|
|
16
|
+
|
|
17
|
+
if params and params[0] in ("self", "cls", "mcs"):
|
|
18
|
+
return args[1:]
|
|
19
|
+
|
|
20
|
+
return args
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def gen_cache_key(
|
|
24
|
+
func: Callable,
|
|
25
|
+
args: tuple,
|
|
26
|
+
kwargs: dict,
|
|
27
|
+
prefix: str | None = None,
|
|
28
|
+
) -> str:
|
|
29
|
+
cleaned_args = clean_args(args, func)
|
|
30
|
+
sorted_kwargs = dict(sorted(kwargs.items()))
|
|
31
|
+
|
|
32
|
+
data = {
|
|
33
|
+
"func_name": func.__name__,
|
|
34
|
+
"args": cleaned_args,
|
|
35
|
+
"kwargs": sorted_kwargs,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
key_hash = hashlib.sha256(
|
|
39
|
+
json.dumps(data, cls=CustomJSONEncoder, sort_keys=True).encode()
|
|
40
|
+
).hexdigest()
|
|
41
|
+
|
|
42
|
+
base_key = f"cache:{key_hash}"
|
|
43
|
+
if prefix:
|
|
44
|
+
return f"cache:{prefix}:{key_hash}"
|
|
45
|
+
return base_key
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: simple-redis-cache
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A library that simplifies working with Redis in Python
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: redis>=8.0.1
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# simple-redis-cache
|
|
12
|
+
|
|
13
|
+
[](https://hotpotato89.github.io/simple-redis-cache/coverage/)
|
|
14
|
+
|
|
15
|
+
Простой декоратор для кэширования асинхронных функций в Redis.
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## Особенности
|
|
19
|
+
|
|
20
|
+
- **Автоматическая генерация ключей** — ключи создаются на основе имени функции и аргументов
|
|
21
|
+
- **Инвалидация по префиксу** — очищайте кэш группами
|
|
22
|
+
- **Кастомный JSON-энкодер** — поддерживает `datetime`, `Decimal`, `UUID`, Pydantic-модели
|
|
23
|
+
- **Устойчивость к ошибкам** — ошибки Redis не ломают приложение
|
|
24
|
+
- **Гибкая настройка** — можно передать свой логгер
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
## Установка
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install simple-redis-cache
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Пример
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from redis.asyncio import Redis
|
|
38
|
+
from simple_redis_cache import Cache
|
|
39
|
+
|
|
40
|
+
redis = Redis()
|
|
41
|
+
cache = Cache(redis)
|
|
42
|
+
|
|
43
|
+
@cache.cache(ttl=60, prefix="user")
|
|
44
|
+
async def get_user(user_id: int):
|
|
45
|
+
return {"id": user_id, "name": "Alice"}
|
|
46
|
+
|
|
47
|
+
# Первый вызов — вычисляется, второй — из кэша
|
|
48
|
+
r1 = await get_user(1)
|
|
49
|
+
r2 = await get_user(1)
|
|
50
|
+
|
|
51
|
+
# Одинаковый результат
|
|
52
|
+
print(r1 == r2)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Инвалидация
|
|
56
|
+
```python
|
|
57
|
+
await cache.invalidate_cache(prefix="user")
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Лицензия
|
|
61
|
+
[**MIT**](LICENSE)
|
|
62
|
+
## Автор
|
|
63
|
+
[**hotpotato89**](https://github.com/hotpotato89)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
simple_redis_cache/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
simple_redis_cache/cache.py,sha256=RWYzIpW_pd6P7kFmFrQf96odyfn-cJ5yMk10uZVjF7k,4601
|
|
4
|
+
simple_redis_cache/encoder.py,sha256=91hcQAN-abedsDadE4V8_CIrx-Du1ejzxzZ-H4FvHYU,489
|
|
5
|
+
simple_redis_cache/key_generator.py,sha256=WyE6j6Kh5TiCsIu97r_O_QyodFqMYtn4tiRQGgLSbJ0,1005
|
|
6
|
+
simple_redis_cache-0.1.0.dist-info/licenses/LICENSE,sha256=0RgGruNnQUXRffWn19iCDQjEsfq9objR3dD59F1sbAA,1068
|
|
7
|
+
simple_redis_cache-0.1.0.dist-info/METADATA,sha256=vJjEqhpT9Equm0t2RUH9toE9TMuvlosVtrp-o6nEwgw,1858
|
|
8
|
+
simple_redis_cache-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
9
|
+
simple_redis_cache-0.1.0.dist-info/top_level.txt,sha256=6EVX-_yUvZjX5AVXsOWxDLWaZHMBiB1Fy2eGAtAqojM,28
|
|
10
|
+
simple_redis_cache-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hotpotato89
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|