]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/python/osrf/cache.py
2a8d30a0310546e587e5cd1e6fbe38f965c968dc
[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
11 class CacheException(Exception):
12     def __init__(self, info):
13         self.info = info
14     def __str__(self):
15         return "%s: %s" % (self.__class__.__name__, self.info)
16
17 class CacheClient(object):
18     def __init__(self, servers=None):
19         ''' If no servers are provided, this instance will use 
20             the global memcache connection.
21             servers takes the form ['server:port', 'server2:port2', ...]
22             '''
23         global _client
24         if servers:
25             self.client = memcache.Client(server, debug=0)
26         else:
27             if not _client:
28                 raise CacheException("not connected to any memcache servers.  try CacheClient.connect(servers)")
29             self.client = _client
30
31     def put(self, key, val, timeout=0):
32         self.client.set(key, osrfObjectToJSON(val), timeout)
33
34     def get(self, key):
35         return osrfJSONToObject(self.client.get(key) or "null")
36
37     @staticmethod
38     def connect(svrs):
39         global _client
40         _client = memcache.Client(svrs, debug=0)
41
42