1# ext/beaker_cache.py 2# Copyright 2006-2023 the Mako authors and contributors <see AUTHORS file> 3# 4# This module is part of Mako and is released under 5# the MIT License: http://www.opensource.org/licenses/mit-license.php 6 7"""Provide a :class:`.CacheImpl` for the Beaker caching system.""" 8 9from mako import exceptions 10from mako.cache import CacheImpl 11 12try: 13 from beaker import cache as beaker_cache 14except: 15 has_beaker = False 16else: 17 has_beaker = True 18 19_beaker_cache = None 20 21 22class BeakerCacheImpl(CacheImpl): 23 24 """A :class:`.CacheImpl` provided for the Beaker caching system. 25 26 This plugin is used by default, based on the default 27 value of ``'beaker'`` for the ``cache_impl`` parameter of the 28 :class:`.Template` or :class:`.TemplateLookup` classes. 29 30 """ 31 32 def __init__(self, cache): 33 if not has_beaker: 34 raise exceptions.RuntimeException( 35 "Can't initialize Beaker plugin; Beaker is not installed." 36 ) 37 global _beaker_cache 38 if _beaker_cache is None: 39 if "manager" in cache.template.cache_args: 40 _beaker_cache = cache.template.cache_args["manager"] 41 else: 42 _beaker_cache = beaker_cache.CacheManager() 43 super().__init__(cache) 44 45 def _get_cache(self, **kw): 46 expiretime = kw.pop("timeout", None) 47 if "dir" in kw: 48 kw["data_dir"] = kw.pop("dir") 49 elif self.cache.template.module_directory: 50 kw["data_dir"] = self.cache.template.module_directory 51 52 if "manager" in kw: 53 kw.pop("manager") 54 55 if kw.get("type") == "memcached": 56 kw["type"] = "ext:memcached" 57 58 if "region" in kw: 59 region = kw.pop("region") 60 cache = _beaker_cache.get_cache_region(self.cache.id, region, **kw) 61 else: 62 cache = _beaker_cache.get_cache(self.cache.id, **kw) 63 cache_args = {"starttime": self.cache.starttime} 64 if expiretime: 65 cache_args["expiretime"] = expiretime 66 return cache, cache_args 67 68 def get_or_create(self, key, creation_function, **kw): 69 cache, kw = self._get_cache(**kw) 70 return cache.get(key, createfunc=creation_function, **kw) 71 72 def put(self, key, value, **kw): 73 cache, kw = self._get_cache(**kw) 74 cache.put(key, value, **kw) 75 76 def get(self, key, **kw): 77 cache, kw = self._get_cache(**kw) 78 return cache.get(key, **kw) 79 80 def invalidate(self, key, **kw): 81 cache, kw = self._get_cache(**kw) 82 cache.remove_value(key, **kw) 83