python (3.12.0)
1 # SPDX-FileCopyrightText: 2015 Eric Larson
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 """
6 The cache object API for implementing caches. The default is a thread
7 safe in-memory dictionary.
8 """
9 from threading import Lock
10
11
12 class ESC[4;38;5;81mBaseCache(ESC[4;38;5;149mobject):
13
14 def get(self, key):
15 raise NotImplementedError()
16
17 def set(self, key, value, expires=None):
18 raise NotImplementedError()
19
20 def delete(self, key):
21 raise NotImplementedError()
22
23 def close(self):
24 pass
25
26
27 class ESC[4;38;5;81mDictCache(ESC[4;38;5;149mBaseCache):
28
29 def __init__(self, init_dict=None):
30 self.lock = Lock()
31 self.data = init_dict or {}
32
33 def get(self, key):
34 return self.data.get(key, None)
35
36 def set(self, key, value, expires=None):
37 with self.lock:
38 self.data.update({key: value})
39
40 def delete(self, key):
41 with self.lock:
42 if key in self.data:
43 self.data.pop(key)
44
45
46 class ESC[4;38;5;81mSeparateBodyBaseCache(ESC[4;38;5;149mBaseCache):
47 """
48 In this variant, the body is not stored mixed in with the metadata, but is
49 passed in (as a bytes-like object) in a separate call to ``set_body()``.
50
51 That is, the expected interaction pattern is::
52
53 cache.set(key, serialized_metadata)
54 cache.set_body(key)
55
56 Similarly, the body should be loaded separately via ``get_body()``.
57 """
58 def set_body(self, key, body):
59 raise NotImplementedError()
60
61 def get_body(self, key):
62 """
63 Return the body as file-like object.
64 """
65 raise NotImplementedError()