X-Git-Url: https://git.kaliko.me/?a=blobdiff_plain;f=sima%2Flib%2Fcache.py;h=2640bf01db39101712ad0c6278c878152c2ba923;hb=HEAD;hp=ebed3fcb3977bf12741163ff35c4a50f25e27f11;hpb=71500abd7ef16784d027a8a20aa28b06e8a13a4f;p=mpd-sima.git diff --git a/sima/lib/cache.py b/sima/lib/cache.py index ebed3fc..2640bf0 100644 --- a/sima/lib/cache.py +++ b/sima/lib/cache.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -# Copyright (c) 2014 Jack Kaliko +# Copyright (c) 2014, 2021 kaliko # Copyright (c) 2012, 2013 Eric Larson # # This program is free software: you can redistribute it and/or modify @@ -23,7 +23,6 @@ dictionary, which in turns means it is not threadsafe for writing. """ import os -import base64 import codecs from hashlib import md5 @@ -36,13 +35,16 @@ from ..utils.filelock import FileLock class BaseCache: def get(self, key): - raise NotImplemented() + """Get cache value""" + raise NotImplementedError def set(self, key, value): - raise NotImplemented() + """Set cache value""" + raise NotImplementedError def delete(self, key): - raise NotImplemented() + """Remove cache value""" + raise NotImplementedError class DictCache(BaseCache): @@ -71,10 +73,10 @@ class FileCache: self.forever = forever if not os.path.isdir(self.directory): - os.mkdir(self.directory) + os.makedirs(self.directory, mode=0o755) - def encode(self, x): - return md5(x.encode('utf-8')).hexdigest() + def encode(self, val): + return md5(val.encode('utf-8')).hexdigest() def _fn(self, name): return os.path.join(self.directory, self.encode(name)) @@ -83,13 +85,20 @@ class FileCache: name = self._fn(key) if os.path.exists(name): return load(codecs.open(name, 'rb')) + return None def set(self, key, value): name = self._fn(key) with FileLock(name): - with codecs.open(name, 'w+b') as fh: - dump(value, fh) + with codecs.open(name, 'w+b') as flh: + dump(value, flh) def delete(self, key): if not self.forever: os.remove(self._fn(key)) + + def __iter__(self): + for dirpath, _, filenames in os.walk(self.directory): + for item in filenames: + name = os.path.join(dirpath, item) + yield load(codecs.open(name, 'rb'))