MCPcopy Index your code
hub / github.com/long2ice/fastapi-cache / InMemoryBackend

Class InMemoryBackend

fastapi_cache/backends/inmemory.py:15–61  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

13
14
15class InMemoryBackend(Backend):
16 _store: Dict[str, Value] = {}
17 _lock = Lock()
18
19 @property
20 def _now(self) -> int:
21 return int(time.time())
22
23 def _get(self, key: str) -> Optional[Value]:
24 v = self._store.get(key)
25 if v:
26 if v.ttl_ts < self._now:
27 del self._store[key]
28 else:
29 return v
30 return None
31
32 async def get_with_ttl(self, key: str) -> Tuple[int, Optional[bytes]]:
33 async with self._lock:
34 v = self._get(key)
35 if v:
36 return v.ttl_ts - self._now, v.data
37 return 0, None
38
39 async def get(self, key: str) -> Optional[bytes]:
40 async with self._lock:
41 v = self._get(key)
42 if v:
43 return v.data
44 return None
45
46 async def set(self, key: str, value: bytes, expire: Optional[int] = None) -> None:
47 async with self._lock:
48 self._store[key] = Value(value, self._now + (expire or 0))
49
50 async def clear(self, namespace: Optional[str] = None, key: Optional[str] = None) -> int:
51 count = 0
52 if namespace:
53 keys = list(self._store.keys())
54 for key in keys:
55 if key.startswith(namespace):
56 del self._store[key]
57 count += 1
58 elif key:
59 del self._store[key]
60 count += 1
61 return count

Callers 2

_init_cacheFunction · 0.90
lifespanFunction · 0.90

Calls

no outgoing calls

Tested by 1

_init_cacheFunction · 0.72