beaker_cache.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """Provide a :class:`.CacheImpl` for the Beaker caching system."""
  2. from mako import exceptions
  3. from mako.cache import CacheImpl
  4. try:
  5. from beaker import cache as beaker_cache
  6. except:
  7. has_beaker = False
  8. else:
  9. has_beaker = True
  10. _beaker_cache = None
  11. class BeakerCacheImpl(CacheImpl):
  12. """A :class:`.CacheImpl` provided for the Beaker caching system.
  13. This plugin is used by default, based on the default
  14. value of ``'beaker'`` for the ``cache_impl`` parameter of the
  15. :class:`.Template` or :class:`.TemplateLookup` classes.
  16. """
  17. def __init__(self, cache):
  18. if not has_beaker:
  19. raise exceptions.RuntimeException(
  20. "Can't initialize Beaker plugin; Beaker is not installed.")
  21. global _beaker_cache
  22. if _beaker_cache is None:
  23. if 'manager' in cache.template.cache_args:
  24. _beaker_cache = cache.template.cache_args['manager']
  25. else:
  26. _beaker_cache = beaker_cache.CacheManager()
  27. super(BeakerCacheImpl, self).__init__(cache)
  28. def _get_cache(self, **kw):
  29. expiretime = kw.pop('timeout', None)
  30. if 'dir' in kw:
  31. kw['data_dir'] = kw.pop('dir')
  32. elif self.cache.template.module_directory:
  33. kw['data_dir'] = self.cache.template.module_directory
  34. if 'manager' in kw:
  35. kw.pop('manager')
  36. if kw.get('type') == 'memcached':
  37. kw['type'] = 'ext:memcached'
  38. if 'region' in kw:
  39. region = kw.pop('region')
  40. cache = _beaker_cache.get_cache_region(self.cache.id, region, **kw)
  41. else:
  42. cache = _beaker_cache.get_cache(self.cache.id, **kw)
  43. cache_args = {'starttime': self.cache.starttime}
  44. if expiretime:
  45. cache_args['expiretime'] = expiretime
  46. return cache, cache_args
  47. def get_or_create(self, key, creation_function, **kw):
  48. cache, kw = self._get_cache(**kw)
  49. return cache.get(key, createfunc=creation_function, **kw)
  50. def put(self, key, value, **kw):
  51. cache, kw = self._get_cache(**kw)
  52. cache.put(key, value, **kw)
  53. def get(self, key, **kw):
  54. cache, kw = self._get_cache(**kw)
  55. return cache.get(key, **kw)
  56. def invalidate(self, key, **kw):
  57. cache, kw = self._get_cache(**kw)
  58. cache.remove_value(key, **kw)