]> kaliko git repositories - mpd-sima.git/blob - sima/lib/cache.py
ebed3fcb3977bf12741163ff35c4a50f25e27f11
[mpd-sima.git] / sima / lib / cache.py
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2014 Jack Kaliko <kaliko@azylum.org>
4 # Copyright (c) 2012, 2013 Eric Larson <eric@ionrock.org>
5 #
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.
10 #
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.
15 #
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/>.
18 #
19 #
20 """
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.
23 """
24
25 import os
26 import base64
27 import codecs
28
29 from hashlib import md5
30 from pickle import load, dump
31 from threading import Lock
32
33 from ..utils.filelock import FileLock
34
35
36 class BaseCache:
37
38     def get(self, key):
39         raise NotImplemented()
40
41     def set(self, key, value):
42         raise NotImplemented()
43
44     def delete(self, key):
45         raise NotImplemented()
46
47
48 class DictCache(BaseCache):
49
50     def __init__(self, init_dict=None):
51         self.lock = Lock()
52         self.data = init_dict or {}
53
54     def get(self, key):
55         return self.data.get(key, None)
56
57     def set(self, key, value):
58         with self.lock:
59             self.data.update({key: value})
60
61     def delete(self, key):
62         with self.lock:
63             if key in self.data:
64                 self.data.pop(key)
65
66
67 class FileCache:
68
69     def __init__(self, directory, forever=False):
70         self.directory = directory
71         self.forever = forever
72
73         if not os.path.isdir(self.directory):
74             os.mkdir(self.directory)
75
76     def encode(self, x):
77         return md5(x.encode('utf-8')).hexdigest()
78
79     def _fn(self, name):
80         return os.path.join(self.directory, self.encode(name))
81
82     def get(self, key):
83         name = self._fn(key)
84         if os.path.exists(name):
85             return load(codecs.open(name, 'rb'))
86
87     def set(self, key, value):
88         name = self._fn(key)
89         with FileLock(name):
90             with codecs.open(name, 'w+b') as fh:
91                 dump(value, fh)
92
93     def delete(self, key):
94         if not self.forever:
95             os.remove(self._fn(key))