pycacheable 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.
- pycacheable/__init__.py +0 -0
- pycacheable/backend_memory.py +48 -0
- pycacheable/backend_sqlite.py +70 -0
- pycacheable/cache_base.py +19 -0
- pycacheable/cacheable.py +53 -0
- pycacheable/hashing.py +109 -0
- pycacheable-0.1.0.dist-info/METADATA +163 -0
- pycacheable-0.1.0.dist-info/RECORD +11 -0
- pycacheable-0.1.0.dist-info/WHEEL +5 -0
- pycacheable-0.1.0.dist-info/licenses/LICENSE +21 -0
- pycacheable-0.1.0.dist-info/top_level.txt +1 -0
pycacheable/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import pickle
|
|
2
|
+
import threading
|
|
3
|
+
import time
|
|
4
|
+
from typing import Any, Dict, Optional, Tuple, OrderedDict
|
|
5
|
+
|
|
6
|
+
from src.pycacheable.cache_base import CacheBase
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class InMemoryCache(CacheBase):
|
|
10
|
+
def __init__(self, max_entries: int = 1024):
|
|
11
|
+
self._store: "OrderedDict[str, Tuple[float, bytes]]" = OrderedDict()
|
|
12
|
+
self._lock = threading.RLock()
|
|
13
|
+
self._max_entries = max_entries
|
|
14
|
+
|
|
15
|
+
def get(self, key: str) -> Tuple[bool, Any, str]:
|
|
16
|
+
with self._lock:
|
|
17
|
+
entry = self._store.get(key)
|
|
18
|
+
now = time.time()
|
|
19
|
+
if not entry:
|
|
20
|
+
return False, None, "MISS"
|
|
21
|
+
expire_at, payload = entry
|
|
22
|
+
if expire_at and expire_at < now:
|
|
23
|
+
self._store.pop(key, None)
|
|
24
|
+
return False, None, "EXPIRE"
|
|
25
|
+
|
|
26
|
+
self._store.move_to_end(key)
|
|
27
|
+
return True, pickle.loads(payload), "HIT"
|
|
28
|
+
|
|
29
|
+
def set(self, key: str, value: Any, ttl_seconds: Optional[int]):
|
|
30
|
+
with self._lock:
|
|
31
|
+
expire_at = (time.time() + ttl_seconds) if ttl_seconds else 0.0
|
|
32
|
+
payload = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL)
|
|
33
|
+
self._store[key] = (expire_at, payload)
|
|
34
|
+
self._store.move_to_end(key)
|
|
35
|
+
while len(self._store) > self._max_entries:
|
|
36
|
+
self._store.popitem(last=False)
|
|
37
|
+
|
|
38
|
+
def clear(self):
|
|
39
|
+
with self._lock:
|
|
40
|
+
self._store.clear()
|
|
41
|
+
|
|
42
|
+
def info(self) -> Dict[str, Any]:
|
|
43
|
+
with self._lock:
|
|
44
|
+
return {
|
|
45
|
+
"backend": "InMemoryCache",
|
|
46
|
+
"size": len(self._store),
|
|
47
|
+
"max_entries": self._max_entries,
|
|
48
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import pickle
|
|
3
|
+
import sqlite3
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Dict, Optional, Tuple
|
|
7
|
+
|
|
8
|
+
from src.pycacheable.cache_base import CacheBase
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SQLiteCache(CacheBase):
|
|
12
|
+
def __init__(self, path: str):
|
|
13
|
+
self._path = path
|
|
14
|
+
self._lock = threading.RLock()
|
|
15
|
+
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
|
16
|
+
|
|
17
|
+
with self._conn() as conn:
|
|
18
|
+
conn.execute("""
|
|
19
|
+
CREATE TABLE IF NOT EXISTS cache
|
|
20
|
+
(
|
|
21
|
+
k
|
|
22
|
+
TEXT
|
|
23
|
+
PRIMARY
|
|
24
|
+
KEY,
|
|
25
|
+
expire_at
|
|
26
|
+
REAL,
|
|
27
|
+
v
|
|
28
|
+
BLOB
|
|
29
|
+
)
|
|
30
|
+
""")
|
|
31
|
+
|
|
32
|
+
conn.execute("PRAGMA journal_mode=WAL;")
|
|
33
|
+
|
|
34
|
+
def _conn(self):
|
|
35
|
+
return sqlite3.connect(self._path, timeout=30, isolation_level=None)
|
|
36
|
+
|
|
37
|
+
def get(self, key: str) -> Tuple[bool, Any, str]:
|
|
38
|
+
with self._lock, self._conn() as conn:
|
|
39
|
+
row = conn.execute("SELECT expire_at, v FROM cache WHERE k=?", (key,)).fetchone()
|
|
40
|
+
now = time.time()
|
|
41
|
+
if not row:
|
|
42
|
+
return False, None, "MISS"
|
|
43
|
+
expire_at, blob = row
|
|
44
|
+
if expire_at and expire_at < now:
|
|
45
|
+
conn.execute("DELETE FROM cache WHERE k=?", (key,))
|
|
46
|
+
return False, None, "EXPIRE"
|
|
47
|
+
return True, pickle.loads(blob), "HIT"
|
|
48
|
+
|
|
49
|
+
def set(self, key: str, value: Any, ttl_seconds: Optional[int]):
|
|
50
|
+
expire_at = (time.time() + ttl_seconds) if ttl_seconds else 0.0
|
|
51
|
+
blob = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL)
|
|
52
|
+
with self._lock, self._conn() as conn:
|
|
53
|
+
conn.execute(
|
|
54
|
+
"REPLACE INTO cache (k, expire_at, v) VALUES (?, ?, ?)",
|
|
55
|
+
(key, expire_at, sqlite3.Binary(blob))
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
def clear(self):
|
|
59
|
+
with self._lock, self._conn() as conn:
|
|
60
|
+
conn.execute("DELETE FROM cache")
|
|
61
|
+
|
|
62
|
+
def info(self) -> Dict[str, Any]:
|
|
63
|
+
with self._lock, self._conn() as conn:
|
|
64
|
+
row = conn.execute("SELECT COUNT(*) FROM cache").fetchone()
|
|
65
|
+
size = int(row[0]) if row else 0
|
|
66
|
+
return {
|
|
67
|
+
"backend": "SQLiteCache",
|
|
68
|
+
"size": size,
|
|
69
|
+
"path": self._path,
|
|
70
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class CacheBase(ABC):
|
|
5
|
+
@abstractmethod
|
|
6
|
+
def get(self, **args):
|
|
7
|
+
pass
|
|
8
|
+
|
|
9
|
+
@abstractmethod
|
|
10
|
+
def set(self, **args):
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
@abstractmethod
|
|
14
|
+
def clear(self, **args):
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
@abstractmethod
|
|
18
|
+
def info(self, **args):
|
|
19
|
+
pass
|
pycacheable/cacheable.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
from typing import Any, Callable, Dict, Optional, Tuple
|
|
3
|
+
|
|
4
|
+
from src.pycacheable.backend_sqlite import SQLiteCache
|
|
5
|
+
from src.pycacheable.hashing import _build_key_from_call
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def cacheable(
|
|
9
|
+
ttl: Optional[int] = 300,
|
|
10
|
+
backend: Optional[object] = None,
|
|
11
|
+
*,
|
|
12
|
+
include_self: bool = False,
|
|
13
|
+
key_fn: Optional[Callable[[Callable, Tuple[Any, ...], Dict[str, Any]], str]] = None,
|
|
14
|
+
logger: Optional[Callable[[str], None]] = None,
|
|
15
|
+
backend_factory: Optional[Callable[..., object]] = None,
|
|
16
|
+
):
|
|
17
|
+
default_backend = backend or SQLiteCache(path="./.cache/db.sqlite3")
|
|
18
|
+
|
|
19
|
+
def decorator(func: Callable):
|
|
20
|
+
@functools.wraps(func)
|
|
21
|
+
def wrapper(*args, **kwargs):
|
|
22
|
+
be = getattr(wrapper, "cache_backend", None)
|
|
23
|
+
if be is None and backend_factory is not None:
|
|
24
|
+
try:
|
|
25
|
+
be = backend_factory(*args, **kwargs)
|
|
26
|
+
except TypeError:
|
|
27
|
+
be = backend_factory(args[0]) if args else None
|
|
28
|
+
if be is None:
|
|
29
|
+
be = default_backend
|
|
30
|
+
|
|
31
|
+
key = (key_fn(func, args, kwargs)
|
|
32
|
+
if key_fn else _build_key_from_call(func, args, kwargs, include_self))
|
|
33
|
+
|
|
34
|
+
hit, value, status = be.get(key)
|
|
35
|
+
if hit:
|
|
36
|
+
if logger: logger(f"[CACHE {status}] {func.__qualname__} {key[:10]}…")
|
|
37
|
+
return value
|
|
38
|
+
|
|
39
|
+
if logger: logger(f"[CACHE {status}] {func.__qualname__} {key[:10]}… -> calling")
|
|
40
|
+
result = func(*args, **kwargs)
|
|
41
|
+
try:
|
|
42
|
+
be.set(key, result, ttl)
|
|
43
|
+
if logger: logger(f"[CACHE SET] {func.__qualname__} {key[:10]}… ttl={ttl}")
|
|
44
|
+
except Exception as e:
|
|
45
|
+
if logger: logger(f"[CACHE ERROR SET] {func.__qualname__}: {e}")
|
|
46
|
+
return result
|
|
47
|
+
|
|
48
|
+
wrapper.cache_backend = default_backend
|
|
49
|
+
wrapper.cache_clear = lambda: wrapper.cache_backend.clear()
|
|
50
|
+
wrapper.cache_info = lambda: wrapper.cache_backend.info()
|
|
51
|
+
return wrapper
|
|
52
|
+
|
|
53
|
+
return decorator
|
pycacheable/hashing.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import datetime as dt
|
|
4
|
+
import decimal
|
|
5
|
+
import enum
|
|
6
|
+
import hashlib
|
|
7
|
+
import inspect
|
|
8
|
+
import json
|
|
9
|
+
import pathlib
|
|
10
|
+
import pickle
|
|
11
|
+
import uuid
|
|
12
|
+
from typing import Any, Mapping, Iterable
|
|
13
|
+
from typing import Callable, Dict, Tuple
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _to_canonical(obj: Any) -> Any:
|
|
17
|
+
if obj is None or isinstance(obj, (bool, int, float, str)):
|
|
18
|
+
return obj
|
|
19
|
+
|
|
20
|
+
if isinstance(obj, decimal.Decimal):
|
|
21
|
+
return str(obj)
|
|
22
|
+
if isinstance(obj, uuid.UUID):
|
|
23
|
+
return str(obj)
|
|
24
|
+
|
|
25
|
+
if isinstance(obj, (dt.datetime, dt.date, dt.time)):
|
|
26
|
+
if isinstance(obj, dt.datetime):
|
|
27
|
+
if obj.tzinfo is None:
|
|
28
|
+
obj = obj.replace(tzinfo=dt.timezone.utc) # padroniza se vier naive
|
|
29
|
+
return obj.astimezone(dt.timezone.utc).isoformat(timespec="microseconds")
|
|
30
|
+
if isinstance(obj, dt.date):
|
|
31
|
+
return obj.isoformat()
|
|
32
|
+
if isinstance(obj, dt.time):
|
|
33
|
+
if obj.tzinfo is None:
|
|
34
|
+
obj = obj.replace(tzinfo=dt.timezone.utc)
|
|
35
|
+
return obj.isoformat(timespec="microseconds")
|
|
36
|
+
|
|
37
|
+
if isinstance(obj, pathlib.Path):
|
|
38
|
+
return str(obj)
|
|
39
|
+
if isinstance(obj, enum.Enum):
|
|
40
|
+
return obj.value if isinstance(obj.value, (str, int, float, bool)) else obj.name
|
|
41
|
+
|
|
42
|
+
if isinstance(obj, set):
|
|
43
|
+
return sorted(_to_canonical(x) for x in obj)
|
|
44
|
+
if isinstance(obj, tuple):
|
|
45
|
+
return ["__tuple__", *(_to_canonical(x) for x in obj)] # preserva semântica
|
|
46
|
+
|
|
47
|
+
if isinstance(obj, Mapping):
|
|
48
|
+
return {str(k): _to_canonical(v) for k, v in sorted(obj.items(), key=lambda kv: str(kv[0]))}
|
|
49
|
+
|
|
50
|
+
if isinstance(obj, Iterable) and not isinstance(obj, (str, bytes, bytearray)):
|
|
51
|
+
return [_to_canonical(x) for x in obj]
|
|
52
|
+
|
|
53
|
+
if isinstance(obj, (bytes, bytearray, memoryview)):
|
|
54
|
+
return {"__bytes__": bytes(obj).hex()}
|
|
55
|
+
|
|
56
|
+
try:
|
|
57
|
+
import numpy as np # type: ignore
|
|
58
|
+
if isinstance(obj, (np.generic,)): # np.int64, np.float32 etc.
|
|
59
|
+
return obj.item()
|
|
60
|
+
if isinstance(obj, (np.ndarray,)):
|
|
61
|
+
return {"__ndarray__": obj.tolist(), "dtype": str(obj.dtype), "shape": obj.shape}
|
|
62
|
+
except Exception:
|
|
63
|
+
pass
|
|
64
|
+
|
|
65
|
+
return {"__type__": type(obj).__name__, "__repr__": repr(obj)}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _json_canonical_dumps(payload: Any) -> bytes:
|
|
69
|
+
canon = _to_canonical(payload)
|
|
70
|
+
return json.dumps(canon, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class EnhancedJSONEncoder(json.JSONEncoder):
|
|
74
|
+
def default(self, o: Any):
|
|
75
|
+
try:
|
|
76
|
+
return {"__type__": type(o).__name__, "__repr__": repr(o)}
|
|
77
|
+
except Exception:
|
|
78
|
+
return super().default(o)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _json_dumps_canonical(obj: Any) -> bytes:
|
|
82
|
+
return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(",", ":"), cls=EnhancedJSONEncoder).encode("utf-8")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _stable_hash(payload: Any) -> str:
|
|
86
|
+
try:
|
|
87
|
+
data = _json_canonical_dumps(payload)
|
|
88
|
+
except Exception:
|
|
89
|
+
data = pickle.dumps(payload, protocol=pickle.HIGHEST_PROTOCOL)
|
|
90
|
+
|
|
91
|
+
return hashlib.sha256(data).hexdigest()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _build_key_from_call(func: Callable, args: Tuple[Any, ...], kwargs: Dict[str, Any], include_self: bool) -> str:
|
|
95
|
+
sig = inspect.signature(func)
|
|
96
|
+
bound = sig.bind_partial(*args, **kwargs)
|
|
97
|
+
bound.apply_defaults()
|
|
98
|
+
items = dict(bound.arguments)
|
|
99
|
+
|
|
100
|
+
if not include_self:
|
|
101
|
+
items.pop("self", None)
|
|
102
|
+
items.pop("cls", None)
|
|
103
|
+
|
|
104
|
+
key_payload = {
|
|
105
|
+
"fn": f"{func.__module__}.{func.__qualname__}",
|
|
106
|
+
"params": items,
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return _stable_hash(key_payload)
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pycacheable
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Decorator de cache para funções e métodos Python, com backends InMemory e SQLite, TTL configurável e hash estável de parâmetros.
|
|
5
|
+
Author-email: Leonardo Pinho <contato@leonardopinho.com>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2025 Leonardo Pinho
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in
|
|
18
|
+
all copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
26
|
+
THE SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/leonardopinho/pycacheable
|
|
29
|
+
Project-URL: Repository, https://github.com/leonardopinho/pycacheable
|
|
30
|
+
Project-URL: Issues, https://github.com/leonardopinho/pycacheable/issues
|
|
31
|
+
Keywords: cache,decorator,sqlite,python,performance,memoization,pycharm
|
|
32
|
+
Classifier: Development Status :: 4 - Beta
|
|
33
|
+
Classifier: Intended Audience :: Developers
|
|
34
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
35
|
+
Classifier: Programming Language :: Python :: 3
|
|
36
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
37
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
40
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
41
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
42
|
+
Classifier: Operating System :: OS Independent
|
|
43
|
+
Requires-Python: >=3.9
|
|
44
|
+
Description-Content-Type: text/markdown
|
|
45
|
+
License-File: LICENSE
|
|
46
|
+
Requires-Dist: typing-extensions>=4.0.0
|
|
47
|
+
Dynamic: license-file
|
|
48
|
+
|
|
49
|
+
# PyCacheable
|
|
50
|
+
|
|
51
|
+
Decorator de cache para métodos e funções Python com backends em memória e SQLite — serialização automática, hash estável de parâmetros, suporte a instância/estado e arquitetura plugável.
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## Problema
|
|
56
|
+
|
|
57
|
+
Em muitos aplicativos Python existem métodos que:
|
|
58
|
+
|
|
59
|
+
- fazem consultas repetidas ao banco de dados ou a APIs externas;
|
|
60
|
+
- recebem os mesmos parâmetros múltiplas vezes;
|
|
61
|
+
- repetem trabalho caro de CPU ou I/O;
|
|
62
|
+
- ou seja: fazem **o mesmo trabalho mais de uma vez**, desperdiçando tempo e recursos.
|
|
63
|
+
|
|
64
|
+
Sem um mecanismo de cache, cada chamada resulta em reexecução completa, levando a latências elevadas, carga extra no banco/serviço, e experiência de usuário piorada.
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## Solução
|
|
69
|
+
|
|
70
|
+
A biblioteca fornece:
|
|
71
|
+
|
|
72
|
+
- Um decorator `@cacheable(...)` que envolve funções ou métodos, gera uma **chave estável** a partir dos parâmetros (serialização canônica + sha256);
|
|
73
|
+
- Suporte a backends:
|
|
74
|
+
- `InMemoryCache`: cache volátil em memória com LRU + TTL.
|
|
75
|
+
- `SQLiteCache`: cache persistente em disco (SQLite) com TTL, ideal para entre execuções ou processos;
|
|
76
|
+
- Logs claros de fluxo: HIT / MISS / EXPIRE — permitindo entender se o cache está funcionando;
|
|
77
|
+
- Métodos auxiliares:
|
|
78
|
+
- `.cache_clear()`, `.cache_info()` no wrapper para inspeção/manutenção;
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## Como usar
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from src.pycacheable.backend_sqlite import SQLiteCache
|
|
86
|
+
from src.pycacheable.backend_memory import InMemoryCache
|
|
87
|
+
from src.pycacheable.cacheable import cacheable
|
|
88
|
+
|
|
89
|
+
mem = InMemoryCache(max_entries=512)
|
|
90
|
+
disk = SQLiteCache(path="./.cache/myapp.sqlite")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class Repo:
|
|
94
|
+
@cacheable(ttl=60, backend=mem)
|
|
95
|
+
def get_user(self, user_id: int) -> dict:
|
|
96
|
+
# consulta cara ao banco
|
|
97
|
+
return {"user_id": user_id, "name": f"user{user_id}"}
|
|
98
|
+
|
|
99
|
+
@cacheable(ttl=300, backend=disk)
|
|
100
|
+
def get_orders(self, user_id: int, status: str = "open") -> list:
|
|
101
|
+
return [{"order_id": 101, "user_id": user_id, "status": status}]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
repo = Repo()
|
|
105
|
+
u1 = repo.get_user(42) # MISS → executa consulta
|
|
106
|
+
u2 = repo.get_user(42) # HIT → retorna cache, consulta não é executada
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
## Benefícios
|
|
112
|
+
|
|
113
|
+
- Menor latência em chamadas repetidas (hit quase instantâneo).
|
|
114
|
+
- Menor carga no banco/serviço, menos I/O repetido.
|
|
115
|
+
- Persistência local (via SQLite) permite cache entre reinícios/processos.
|
|
116
|
+
- Transparente para o usuário da função — apenas aplicar o decorator.
|
|
117
|
+
- Logs e métricas ajudam a monitorar impacto real.
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## Quando usar
|
|
122
|
+
|
|
123
|
+
- Funções/métodos com **resultado determinístico** (mesmos parâmetros → mesmo resultado)
|
|
124
|
+
- Consultas idempotentes e repetidas
|
|
125
|
+
- Cálculos caros de CPU ou I/O
|
|
126
|
+
- Cenários onde latência importa e repetição deve ser evitada
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## Considerações e limites
|
|
131
|
+
|
|
132
|
+
- O cache evita reexecuções **somente** se os parâmetros para o método forem os mesmos e serializáveis.
|
|
133
|
+
- Se o método depende de estados mutáveis fora dos parâmetros (ex.: `self.some_state`), você deve usar `include_self=True` ou custom `key_fn`.
|
|
134
|
+
- TTL é usado para expiração — resultados podem ficar “stale” se parâmetros ou contexto mudarem sem mudar a chave.
|
|
135
|
+
- Embora o backend SQLite seja persistente, ele **não substitui** um cache distribuído (ex.: Redis) em cenários multi‑processo/semi‑distribuídos.
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## Benchmarks
|
|
140
|
+
|
|
141
|
+
Veja resultados reais que medem MISS vs HIT:
|
|
142
|
+
|
|
143
|
+
| Backend | MISS (s) | HIT (s) | Speedup | Calls |
|
|
144
|
+
|----------|-----------|----------|----------|--------|
|
|
145
|
+
| RAW | 0.6827 | — | — | — |
|
|
146
|
+
| InMemory | 0.6630 | 0.000113 | ~5 870× | 1 |
|
|
147
|
+
| SQLite | 0.7157 | 0.000098 | ~7 300× | 1 |
|
|
148
|
+
|
|
149
|
+
O cache reduz o tempo de execução de ~0.68 s para ~0.0001 s — um **speedup superior a 5 000×**.
|
|
150
|
+
|
|
151
|
+
---
|
|
152
|
+
|
|
153
|
+
## Próximos passos
|
|
154
|
+
|
|
155
|
+
- Suporte a funções `async def` (decorator awaitable)
|
|
156
|
+
- Backend Redis / LMDB para cenários distribuídos
|
|
157
|
+
- Métricas e integração com Prometheus
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
## Licença
|
|
162
|
+
|
|
163
|
+
MIT License — veja o arquivo `LICENSE` para detalhes.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
pycacheable/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
pycacheable/backend_memory.py,sha256=KG8u44jJ16Quhr951oJBrNJDIHROf0OEL7yIWfM5CZI,1638
|
|
3
|
+
pycacheable/backend_sqlite.py,sha256=w4ehSE9N2XUInECoTe_xnjM5x1CprZS8LR5i1E9ZyVw,2430
|
|
4
|
+
pycacheable/cache_base.py,sha256=ToC_dRqAJw_L3MKwQU5WkYhLkUrRSgdbxKfoqQL4LKY,306
|
|
5
|
+
pycacheable/cacheable.py,sha256=ZCrZdEfsNpSrN9R3ABPmyKl9Z7O0n0drhKOMnurFMg0,2065
|
|
6
|
+
pycacheable/hashing.py,sha256=4oRSIoFvU8Uf-FitdmHBlbqJB1i8ChtKDjwpzpZ_yjk,3534
|
|
7
|
+
pycacheable-0.1.0.dist-info/licenses/LICENSE,sha256=-JZxc1XvWnZpw2JnH6jFzuLgKVNMrN-sInApa3vcICg,1071
|
|
8
|
+
pycacheable-0.1.0.dist-info/METADATA,sha256=YFd3P7X3QbBoJOjju9ez0LLuSw4M5EGUIuRBXww8DLU,6457
|
|
9
|
+
pycacheable-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
10
|
+
pycacheable-0.1.0.dist-info/top_level.txt,sha256=mdIW77ehuhwiwZKUktjcQssACUrfMwSudWQZvrc99rA,12
|
|
11
|
+
pycacheable-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Leonardo Pinho
|
|
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
|
|
13
|
+
all 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
|
|
21
|
+
THE SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pycacheable
|