-
Notifications
You must be signed in to change notification settings - Fork 53
/
cache.py
62 lines (47 loc) · 1.25 KB
/
cache.py
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
61
62
from abc import ABC, abstractmethod
import uuid
class Cache(ABC):
@abstractmethod
def generate_id(self, *args, **kwargs):
pass
@abstractmethod
def get(self, id, field):
pass
@abstractmethod
def get_all(self, field_list) -> list:
pass
@abstractmethod
def set(self, id, field, value):
pass
@abstractmethod
def delete(self, id):
pass
class MemoryCache(Cache):
def __init__(self):
self.cache = {}
def generate_id(self, *args, **kwargs):
return str(uuid.uuid4())
def set(self, id, field, value):
if id not in self.cache:
self.cache[id] = {}
self.cache[id][field] = value
def get(self, id, field):
if id not in self.cache:
return None
if field not in self.cache[id]:
return None
return self.cache[id][field]
def get_all(self, field_list) -> list:
return [
{
"id": id,
**{
field: self.get(id=id, field=field)
for field in field_list
}
}
for id in self.cache
]
def delete(self, id):
if id in self.cache:
del self.cache[id]