Cache API

This commit is contained in:
2023-04-29 18:23:20 -04:00
parent a3413e382c
commit a83e8cb22c
5 changed files with 89 additions and 54 deletions

14
util.py
View File

@@ -16,6 +16,15 @@ except ImportError:
from typing import Any, Union, AsyncGenerator, Iterable, Tuple, Callable
class Cached(object):
def __init__(self, base, ts=None):
self._base = base
self._ts = ts
def __getattr__(self, key):
return getattr(self._base, key)
def __getitem__(self, key):
return getitem(self._base, key)
class Store(object):
def __init__(self, database: Union[sqlite3.Connection, str]=':memory:', synchronous: bool=None, journal_mode: bool=None, default_factory: Union[Callable, None]=None):
self._db = database if isinstance(database, sqlite3.Connection) else sqlite3.connect(database, check_same_thread=False)
@@ -60,8 +69,8 @@ class Mapping(object):
def get(self, key: Union[str, slice], ttl: float=float('inf'), now: float=0, **kw) -> Any:
if isinstance(key, slice):
key, ttl, now = key.start, key.stop, key.step
for row in self._store.execute(f'SELECT value FROM "{self._tbl}" WHERE key = ? AND ts > ? LIMIT 1', (key, (now or time.time()) - ttl)):
return loads(row[0])
for row in self._store.execute(f'SELECT value, ts FROM "{self._tbl}" WHERE key = ? AND ts > ? LIMIT 1', (key, (now or time.time()) - ttl)):
return Cached(loads(row[0]), row[1])
if 'default' in kw:
return kw['default']
elif self._store._default_factory is not None:
@@ -148,6 +157,7 @@ class CacheProxy(object):
return fetch(*args, **kw)
else:
return value
thunk.cached = True
setattr(self, key, thunk)
return thunk