def build_cache_from_config(app):
cfg = app.config
cache_type = cfg.get('CACHE_TYPE')
if cache_type is None:
return None
cache_config = {'CACHE_TYPE': cache_type}
if cache_type == 'redis':
cache_config.update({
'CACHE_KEY_PREFIX': cfg['CACHE_KEY_PREFIX'],
'CACHE_REDIS_HOST': cfg['CACHE_REDIS_HOST'],
'CACHE_REDIS_PORT': cfg['CACHE_REDIS_PORT'],
'CACHE_REDIS_URL': cfg['CACHE_REDIS_URL']
})
cache = Cache(config=cache_config)
return cache
python类Cache()的实例源码
def cache(self):
# Remove annoying depcration warning from flask-cache
from flask.exthook import ExtDeprecationWarning
warnings.simplefilter('ignore', ExtDeprecationWarning)
if hasattr(self, '_cache'):
return self._cache
if CACHE_BACKEND_URI == 'memory://':
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
elif CACHE_BACKEND_URI.startswith('redis://'):
try:
from redis import from_url as redis_from_url
redis_from_url(CACHE_BACKEND_URI)
except:
print('BAD REDIS URL PROVIDED BY (CACHE_BACKEND_URI)')
exit(1)
cache = Cache(app, config={
'CACHE_TYPE': 'redis',
'CACHE_REDIS_URL': CACHE_BACKEND_URI,
'CACHE_DEFAULT_TIMEOUT': 0 # NEVER EXPIRES
})
cache.init_app(self.app)
self._cache = cache
return self._cache
def configure_cache(app, config):
cache_config = {
'CACHE_TYPE': config.get('cache', 'type')
}
if cache_config['CACHE_TYPE'] == 'redis':
cache_config['CACHE_REDIS_HOST'] = config.get('redis', 'host')
cache_config['CACHE_REDIS_PORT'] = config.getint('redis', 'port')
cache = Cache(app, config=cache_config)
return cache
def _config_caching(self):
from flask_cache import Cache
self.cache = Cache(self)