1 | | "Single-process in-memory cache backend." |
2 | | |
3 | | from django.core.cache.backends.base import BaseCache |
4 | | import time |
5 | | |
6 | | class CacheClass(BaseCache): |
7 | | def __init__(self, host, params): |
8 | | BaseCache.__init__(self, params) |
9 | | self._cache = {} |
10 | | self._expire_info = {} |
11 | | |
12 | | max_entries = params.get('max_entries', 300) |
13 | | try: |
14 | | self._max_entries = int(max_entries) |
15 | | except (ValueError, TypeError): |
16 | | self._max_entries = 300 |
17 | | |
18 | | cull_frequency = params.get('cull_frequency', 3) |
19 | | try: |
20 | | self._cull_frequency = int(cull_frequency) |
21 | | except (ValueError, TypeError): |
22 | | self._cull_frequency = 3 |
23 | | |
24 | | def add(self, key, value, timeout=None): |
25 | | if len(self._cache) >= self._max_entries: |
26 | | self._cull() |
27 | | if timeout is None: |
28 | | timeout = self.default_timeout |
29 | | if key not in self._cache.keys(): |
30 | | self._cache[key] = value |
31 | | self._expire_info[key] = time.time() + timeout |
32 | | |
33 | | def get(self, key, default=None): |
34 | | now = time.time() |
35 | | exp = self._expire_info.get(key) |
36 | | if exp is None: |
37 | | return default |
38 | | elif exp < now: |
39 | | del self._cache[key] |
40 | | del self._expire_info[key] |
41 | | return default |
42 | | else: |
43 | | return self._cache[key] |
44 | | |
45 | | def set(self, key, value, timeout=None): |
46 | | if len(self._cache) >= self._max_entries: |
47 | | self._cull() |
48 | | if timeout is None: |
49 | | timeout = self.default_timeout |
50 | | self._cache[key] = value |
51 | | self._expire_info[key] = time.time() + timeout |
52 | | |
53 | | def delete(self, key): |
54 | | try: |
55 | | del self._cache[key] |
56 | | except KeyError: |
57 | | pass |
58 | | try: |
59 | | del self._expire_info[key] |
60 | | except KeyError: |
61 | | pass |
62 | | |
63 | | def has_key(self, key): |
64 | | return key in self._cache |
65 | | |
66 | | def _cull(self): |
67 | | if self._cull_frequency == 0: |
68 | | self._cache.clear() |
69 | | self._expire_info.clear() |
70 | | else: |
71 | | doomed = [k for (i, k) in enumerate(self._cache) if i % self._cull_frequency == 0] |
72 | | for k in doomed: |
73 | | self.delete(k) |