Debian Codegraph @

beanie/odm/cache.py

raw
1 import collections
2 import datetime
3 from datetime import timedelta, timezone
4 from typing import Any
5
6 from pydantic import BaseModel, Field
7
8
9 class CachedItem(BaseModel):
10 timestamp: datetime.datetime = Field(
11 default_factory=lambda: datetime.datetime.now(tz=timezone.utc)
12 )
13 value: Any
14
15
16 class LRUCache:
17 def __init__(self, capacity: int, expiration_time: timedelta):
18 self.capacity: int = capacity
19 self.expiration_time: timedelta = expiration_time
20 self.cache: collections.OrderedDict = collections.OrderedDict()
21
22 def get(self, key) -> CachedItem | None:
23 try:
24 item: CachedItem = self.cache.pop(key)
25 if (
26 datetime.datetime.now(tz=timezone.utc) - item.timestamp
27 > self.expiration_time
28 ):
29 return None
30 self.cache[key] = item
31 return item.value
32 except KeyError:
33 return None
34
35 def set(self, key, value) -> None:
36 try:
37 self.cache.pop(key)
38 except KeyError:
39 if len(self.cache) >= self.capacity:
40 self.cache.popitem(last=False)
41 self.cache[key] = CachedItem(value=value)
42
43 @staticmethod
44 def create_key(*args):
45 return str(args) # TODO think about this