]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/python/osrf/cache.py
added cache delete. updated some logging
[OpenSRF.git] / src / python / osrf / cache.py
1 import memcache
2 from osrf.json import osrfObjectToJSON, osrfJSONToObject
3 from osrf.log import *
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("not connected to any memcache servers.  try CacheClient.connect(servers)")
31             self.client = _client
32
33     def put(self, key, val, timeout=None):
34         global defaultTimeout
35         if timeout is None:
36             timeout = defaultTimeout
37         s = osrfObjectToJSON(val)
38         osrfLogInternal("cache: %s => %s" % (str(key), s))
39         return self.client.set(str(key), s, timeout)
40
41     def get(self, key):
42         o = self.client.get(str(key))
43         osrfLogInternal("cache: fetching %s => %s" % (str(key), o))
44         return osrfJSONToObject(o or "null")
45
46     def delete(self, key):
47         osrfLogInternal("cache: deleting %s" % str(key))
48         self.client.delete(str(key))
49
50     @staticmethod
51     def connect(svrs):
52         global _client
53         osrfLogDebug("cache: connecting to servers %s" % str(svrs))
54         _client = memcache.Client(svrs, debug=1)
55
56