1 # -*- coding: utf-8 -*-
3 # Copyright (c) 2014 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
39 raise NotImplementedError
41 def set(self, key, value):
43 raise NotImplementedError
45 def delete(self, key):
46 """Remove cache value"""
47 raise NotImplementedError
50 class DictCache(BaseCache):
52 def __init__(self, init_dict=None):
54 self.data = init_dict or {}
57 return self.data.get(key, None)
59 def set(self, key, value):
61 self.data.update({key: value})
63 def delete(self, key):
71 def __init__(self, directory, forever=False):
72 self.directory = directory
73 self.forever = forever
75 if not os.path.isdir(self.directory):
76 os.makedirs(self.directory, mode=0o755)
78 def encode(self, val):
79 return md5(val.encode('utf-8')).hexdigest()
82 return os.path.join(self.directory, self.encode(name))
86 if os.path.exists(name):
87 return load(codecs.open(name, 'rb'))
89 def set(self, key, value):
92 with codecs.open(name, 'w+b') as flh:
95 def delete(self, key):
97 os.remove(self._fn(key))
100 for dirpath, _, filenames in os.walk(self.directory):
101 for item in filenames:
102 name = os.path.join(dirpath, item)
103 yield load(codecs.open(name, 'rb'))