diff --git a/goal_tools/caching.py b/goal_tools/caching.py index da80ad3..47b5984 100644 --- a/goal_tools/caching.py +++ b/goal_tools/caching.py @@ -29,13 +29,14 @@ class Cache: """ - def __init__(self, filename): + def __init__(self, filename, preload=True): self._shelf = shelve.open(filename) self._memory = {} - LOG.debug('loading cache into RAM') - for key in self._shelf: - self._memory[key] = self._shelf[key] - LOG.debug('loaded %d items from cache', len(self._memory)) + if preload: + LOG.debug('loading cache into RAM') + for key in self._shelf: + self._memory[key] = self._shelf[key] + LOG.debug('loaded %d items from cache', len(self._memory)) self._data = collections.ChainMap(self._memory, self._shelf) def __contains__(self, key): diff --git a/goal_tools/who_helped/cache.py b/goal_tools/who_helped/cache.py index 7e85670..2917c80 100644 --- a/goal_tools/who_helped/cache.py +++ b/goal_tools/who_helped/cache.py @@ -37,7 +37,8 @@ class CacheRemove(command.Command): return parser def take_action(self, parsed_args): - del self.app.cache[(parsed_args.type, parsed_args.id)] + cache = self.app._load_cache_file(preload=False) + del cache[(parsed_args.type, parsed_args.id)] class CacheShow(command.Command): @@ -57,5 +58,6 @@ class CacheShow(command.Command): return parser def take_action(self, parsed_args): - data = self.app.cache[(parsed_args.type, parsed_args.id)] + cache = self.app._load_cache_file(preload=False) + data = cache[(parsed_args.type, parsed_args.id)] pprint.pprint(data) diff --git a/goal_tools/who_helped/main.py b/goal_tools/who_helped/main.py index 2d16aaa..86aa5fb 100644 --- a/goal_tools/who_helped/main.py +++ b/goal_tools/who_helped/main.py @@ -50,13 +50,21 @@ class WhoHelped(app.App): def initialize_app(self, argv): # Quiet the urllib3 module output coming out of requests. logging.getLogger('urllib3').setLevel(logging.WARNING) + self._cache = None - # Open the cache file. - if self.options.cache_file: - self.cache = caching.Cache(self.options.cache_file) - else: - # Use a dictionary for a memory cache. - self.cache = {} + def _load_cache_file(self, preload=True): + return caching.Cache(self.options.cache_file, preload=preload) + + @property + def cache(self): + if self._cache is None: + # Open the cache file. + if self.options.cache_file: + self._cache = self._load_cache_file() + else: + # Use a dictionary for a memory cache. + self._cache = {} + return self._cache def main(argv=sys.argv[1:]):