forked from mozilla-services/cliquet
/
__init__.py
92 lines (70 loc) · 2.43 KB
/
__init__.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import random
from cliquet import logger
_HEARTBEAT_DELETE_RATE = 0.5
_HEARTBEAT_KEY = '__heartbeat__'
_HEARTBEAT_TTL_SECONDS = 3600
class CacheBase(object):
def __init__(self, *args, **kwargs):
pass
def initialize_schema(self):
"""Create every necessary objects (like tables or indices) in the
backend.
This is excuted when the ``cliquet migrate`` command is ran.
"""
raise NotImplementedError
def flush(self):
"""Delete every values."""
raise NotImplementedError
def ttl(self, key):
"""Obtain the expiration value of the specified `key`.
:param str key: key
:returns: number of seconds or negative if no TTL.
:rtype: float
"""
raise NotImplementedError
def expire(self, key, ttl):
"""Set the expiration value `ttl` for the specified `key`.
:param str key: key
:param float ttl: number of seconds
"""
raise NotImplementedError
def set(self, key, value, ttl=None):
"""Store a value with the specified `key`. If `ttl` is provided,
set an expiration value.
:param str key: key
:param str value: value to store
:param float ttl: expire after number of seconds
"""
raise NotImplementedError
def get(self, key):
"""Obtain the value of the specified `key`.
:param str key: key
:returns: the stored value or None if missing.
:rtype: str
"""
raise NotImplementedError
def delete(self, key):
"""Delete the value of the specified `key`.
:param str key: key
"""
raise NotImplementedError
def heartbeat(backend):
def ping(request):
"""Test that cache backend is operationnal.
:param request: current request object
:type request: :class:`~pyramid:pyramid.request.Request`
:returns: ``True`` is everything is ok, ``False`` otherwise.
:rtype: bool
"""
# No specific case for readonly mode because the cache should
# continue to work in that mode.
try:
if random.random() < _HEARTBEAT_DELETE_RATE:
backend.delete(_HEARTBEAT_KEY)
else:
backend.set(_HEARTBEAT_KEY, 'alive', _HEARTBEAT_TTL_SECONDS)
return True
except:
logger.exception("Heartbeat Failure")
return False
return ping