~jonas-drange/ubuntu-start-page/1252899-mobile-friendly

« back to all changes in this revision

Viewing changes to src/mako/cache.py

  • Committer: Matthew Nuzum
  • Date: 2008-04-18 01:58:53 UTC
  • Revision ID: matthew.nuzum@canonical.com-20080418015853-2b8rf979z2c2exxl
adding files

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from mako import exceptions
 
2
 
 
3
try:
 
4
    import beaker.container as container
 
5
    import beaker.exceptions
 
6
    clsmap = {
 
7
        'memory':container.MemoryContainer,
 
8
        'dbm':container.DBMContainer,
 
9
        'file':container.FileContainer,
 
10
    }
 
11
    try:
 
12
        import beaker.ext.memcached as memcached
 
13
        # XXX HACK: Python 2.3 under some circumstances will import this module
 
14
        #           even though there's no memcached. This ensures its really
 
15
        #           there before adding it.
 
16
        if hasattr(memcached, 'MemcachedContainer'):
 
17
            clsmap['memcached'] = memcached.MemcachedContainer
 
18
    except beaker.exceptions.BeakerException:
 
19
        pass
 
20
except ImportError:
 
21
    container = None
 
22
    clsmap = {}
 
23
 
 
24
class Cache(object):
 
25
    def __init__(self, id, starttime, **kwargs):
 
26
        self.id = id
 
27
        self.starttime = starttime
 
28
        if container is not None:
 
29
            self.context = container.ContainerContext()
 
30
        self._containers = {}
 
31
        self.kwargs = kwargs
 
32
    def put(self, key, value, type='memory', **kwargs):
 
33
        self._get_container(key, type, **kwargs).set_value(value)
 
34
    def get(self, key, type='memory', **kwargs):
 
35
        return self._get_container(key, type, **kwargs).get_value()
 
36
    def _get_container(self, key, type, **kwargs):
 
37
        try:
 
38
            return self._containers[key]
 
39
        except KeyError:
 
40
            if container is None:
 
41
                raise exceptions.RuntimeException("the Beaker package is required to use cache functionality.")
 
42
            kw = self.kwargs.copy()
 
43
            kw.update(kwargs)
 
44
            return self._containers.setdefault(key, clsmap[type](key, self.context, self.id, starttime=self.starttime, **kw))
 
45