1 # -*- coding: utf-8 -*-
3 # Copyright (c) 2014 Jack Kaliko <kaliko@azylum.org>
4 # Copyright (c) 2012, 2013 Eric Larson <eric@ionrock.org>
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 The cache object API for implementing caches. The default is just a
22 dictionary, which in turns means it is not threadsafe for writing.
28 from hashlib import md5
29 from pickle import load, dump
30 from threading import Lock
32 from ..utils.filelock import FileLock
38 raise NotImplemented()
40 def set(self, key, value):
41 raise NotImplemented()
43 def delete(self, key):
44 raise NotImplemented()
47 class DictCache(BaseCache):
49 def __init__(self, init_dict=None):
51 self.data = init_dict or {}
54 return self.data.get(key, None)
56 def set(self, key, value):
58 self.data.update({key: value})
60 def delete(self, key):
68 def __init__(self, directory, forever=False):
69 self.directory = directory
70 self.forever = forever
72 if not os.path.isdir(self.directory):
73 os.mkdir(self.directory)
76 return md5(x.encode('utf-8')).hexdigest()
79 return os.path.join(self.directory, self.encode(name))
83 if os.path.exists(name):
84 return load(codecs.open(name, 'rb'))
86 def set(self, key, value):
89 with codecs.open(name, 'w+b') as fh:
92 def delete(self, key):
94 os.remove(self._fn(key))
97 for dirpath, dirnames, filenames in os.walk(self.directory):
98 for item in filenames:
99 name = os.path.join(dirpath, item)
100 yield load(codecs.open(name, 'rb'))