-
-
Notifications
You must be signed in to change notification settings - Fork 206
Expand file tree
/
Copy pathinmemory.py
More file actions
60 lines (49 loc) · 1.54 KB
/
Copy pathinmemory.py
File metadata and controls
60 lines (49 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import time
from asyncio import Lock
from dataclasses import dataclass
from fastapi_cache.types import Backend
@dataclass
class Value:
data: bytes
ttl_ts: int
class InMemoryBackend(Backend):
_store: dict[str, Value] = {}
_lock = Lock()
@property
def _now(self) -> int:
return int(time.time())
def _get(self, key: str) -> Value | None:
v = self._store.get(key)
if v:
if v.ttl_ts < self._now:
del self._store[key]
else:
return v
return None
async def get_with_ttl(self, key: str) -> tuple[int, bytes | None]:
async with self._lock:
v = self._get(key)
if v:
return v.ttl_ts - self._now, v.data
return 0, None
async def get(self, key: str) -> bytes | None:
async with self._lock:
v = self._get(key)
if v:
return v.data
return None
async def set(self, key: str, value: bytes, expire: int | None = None) -> None:
async with self._lock:
self._store[key] = Value(value, self._now + (expire or 0))
async def clear(self, namespace: str | None = None, key: str | None = None) -> int:
count = 0
if namespace:
keys = list(self._store.keys())
for key in keys:
if key.startswith(namespace):
del self._store[key]
count += 1
elif key:
del self._store[key]
count += 1
return count