]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/python/osrf/cache.py
added a default timeout cache setting
[OpenSRF.git] / src / python / osrf / cache.py
1 import memcache
2 from osrf.json import osrfObjectToJSON, osrfJSONToObject
3
4 '''
5 Abstracted OpenSRF caching interface.
6 Requires memcache: ftp://ftp.tummy.com/pub/python-memcached/
7 '''
8
9 _client = None
10 defaultTimeout = 0
11
12 class CacheException(Exception):
13     def __init__(self, info):
14         self.info = info
15     def __str__(self):
16         return "%s: %s" % (self.__class__.__name__, self.info)
17
18 class CacheClient(object):
19     def __init__(self, servers=None):
20         ''' If no servers are provided, this instance will use 
21             the global memcache connection.
22             servers takes the form ['server:port', 'server2:port2', ...]
23             '''
24         global _client
25         if servers:
26             self.client = memcache.Client(server, debug=0)
27         else:
28             if not _client:
29                 raise CacheException("not connected to any memcache servers.  try CacheClient.connect(servers)")
30             self.client = _client
31
32     def put(self, key, val, timeout=None):
33         global defaultTimeout
34         if timeout is None:
35             timeout = defaultTimeout
36         self.client.set(key, osrfObjectToJSON(val), timeout)
37
38     def get(self, key):
39         return osrfJSONToObject(self.client.get(key) or "null")
40
41     @staticmethod
42     def connect(svrs):
43         global _client
44         _client = memcache.Client(svrs, debug=0)
45
46