1 | from mako import exceptions |
---|
2 | |
---|
3 | try: |
---|
4 | from beaker import cache |
---|
5 | cache = cache.CacheManager() |
---|
6 | except ImportError: |
---|
7 | cache = None |
---|
8 | |
---|
9 | class Cache(object): |
---|
10 | def __init__(self, id, starttime): |
---|
11 | self.id = id |
---|
12 | self.starttime = starttime |
---|
13 | self.def_regions = {} |
---|
14 | |
---|
15 | def put(self, key, value, **kwargs): |
---|
16 | defname = kwargs.pop('defname', None) |
---|
17 | expiretime = kwargs.pop('expiretime', None) |
---|
18 | createfunc = kwargs.pop('createfunc', None) |
---|
19 | |
---|
20 | self._get_cache(defname, **kwargs).put_value(key, starttime=self.starttime, expiretime=expiretime) |
---|
21 | |
---|
22 | def get(self, key, **kwargs): |
---|
23 | defname = kwargs.pop('defname', None) |
---|
24 | expiretime = kwargs.pop('expiretime', None) |
---|
25 | createfunc = kwargs.pop('createfunc', None) |
---|
26 | |
---|
27 | return self._get_cache(defname, **kwargs).get_value(key, starttime=self.starttime, expiretime=expiretime, createfunc=createfunc) |
---|
28 | |
---|
29 | def invalidate(self, key, **kwargs): |
---|
30 | defname = kwargs.pop('defname', None) |
---|
31 | expiretime = kwargs.pop('expiretime', None) |
---|
32 | createfunc = kwargs.pop('createfunc', None) |
---|
33 | |
---|
34 | self._get_cache(defname, **kwargs).remove_value(key, starttime=self.starttime, expiretime=expiretime) |
---|
35 | |
---|
36 | def invalidate_body(self): |
---|
37 | self.invalidate('render_body', defname='render_body') |
---|
38 | |
---|
39 | def invalidate_def(self, name): |
---|
40 | self.invalidate('render_%s' % name, defname='render_%s' % name) |
---|
41 | |
---|
42 | def invalidate_closure(self, name): |
---|
43 | self.invalidate(name, defname=name) |
---|
44 | |
---|
45 | def _get_cache(self, defname, type=None, **kw): |
---|
46 | if not cache: |
---|
47 | raise exceptions.RuntimeException("the Beaker package is required to use cache functionality.") |
---|
48 | if type == 'memcached': |
---|
49 | type = 'ext:memcached' |
---|
50 | if not type: |
---|
51 | (type, kw) = self.def_regions.get(defname, ('memory', {})) |
---|
52 | else: |
---|
53 | self.def_regions[defname] = (type, kw) |
---|
54 | return cache.get_cache(self.id, type=type, **kw) |
---|
55 | |
---|