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.
29 from hashlib import md5
30 from pickle import load, dump
31 from threading import Lock
33 from ..utils.filelock import FileLock
39 raise NotImplemented()
41 def set(self, key, value):
42 raise NotImplemented()
44 def delete(self, key):
45 raise NotImplemented()
48 class DictCache(BaseCache):
50 def __init__(self, init_dict=None):
52 self.data = init_dict or {}
55 return self.data.get(key, None)
57 def set(self, key, value):
59 self.data.update({key: value})
61 def delete(self, key):
69 def __init__(self, directory, forever=False):
70 self.directory = directory
71 self.forever = forever
73 if not os.path.isdir(self.directory):
74 os.mkdir(self.directory)
77 return md5(x.encode('utf-8')).hexdigest()
80 return os.path.join(self.directory, self.encode(name))
84 if os.path.exists(name):
85 return load(codecs.open(name, 'rb'))
87 def set(self, key, value):
90 with codecs.open(name, 'w+b') as fh:
93 def delete(self, key):
95 os.remove(self._fn(key))