]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/python/osrf/cache.py
added a static method to see if there is already a globally connected cache client
[OpenSRF.git] / src / python / osrf / cache.py
1 import memcache
2 from osrf.json import to_json, to_object
3 import osrf.log
4
5 '''
6 Abstracted OpenSRF caching interface.
7 Requires memcache: ftp://ftp.tummy.com/pub/python-memcached/
8 '''
9
10 _client = None
11 defaultTimeout = 0
12
13 class CacheException(Exception):
14     def __init__(self, info):
15         self.info = info
16     def __str__(self):
17         return "%s: %s" % (self.__class__.__name__, self.info)
18
19 class CacheClient(object):
20     def __init__(self, servers=None):
21         ''' If no servers are provided, this instance will use 
22             the global memcache connection.
23             servers takes the form ['server:port', 'server2:port2', ...]
24             '''
25         global _client
26         if servers:
27             self.client = memcache.Client(server, debug=1)
28         else:
29             if not _client:
30                 raise CacheException(
31                     "not connected to any memcache servers."
32                     "try CacheClient.connect(servers)"
33                 )
34             self.client = _client
35
36     def put(self, key, val, timeout=None):
37         global defaultTimeout
38         if timeout is None:
39             timeout = defaultTimeout
40         timeout = int(timeout)
41         json = to_json(val)
42         osrf.log.log_internal("cache: %s => %s" % (str(key), json))
43         return self.client.set(str(key), json, timeout)
44
45     def get(self, key):
46         obj = self.client.get(str(key))
47         osrf.log.log_internal("cache: fetching %s => %s" % (str(key), obj))
48         return to_object(obj or "null")
49
50     def delete(self, key):
51         osrf.log.log_internal("cache: deleting %s" % str(key))
52         self.client.delete(str(key))
53
54     @staticmethod
55     def connect(svrs):
56         global _client
57         osrf.log.log_debug("cache: connecting to servers %s" % str(svrs))
58         _client = memcache.Client(svrs, debug=1)
59
60     @staticmethod
61     def get_client():
62         global _client
63         return _client
64
65