1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2013 Team tiramisu (see AUTHORS for all contributors)
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 # ____________________________________________________________
20 from pickle import dumps, loads
24 __slots__ = ('storage',)
27 def __init__(self, cache_type, storage):
28 self.storage = storage
29 cache_table = 'CREATE TABLE IF NOT EXISTS cache_{0}(path '.format(
31 cache_table += 'text primary key, value text, time real)'
32 self.storage.execute(cache_table)
35 def _sqlite_decode_path(self, path):
41 def _sqlite_encode_path(self, path):
47 def _sqlite_decode(self, value):
50 def _sqlite_encode(self, value):
51 if isinstance(value, list):
55 def setcache(self, cache_type, path, val, time):
56 convert_value = self._sqlite_encode(val)
57 path = self._sqlite_encode_path(path)
58 self.storage.execute("DELETE FROM cache_{0} WHERE path = ?".format(
59 cache_type), (path,), False)
60 self.storage.execute("INSERT INTO cache_{0}(path, value, time) "
61 "VALUES (?, ?, ?)".format(cache_type),
62 (path, convert_value, time))
64 def getcache(self, cache_type, path, exp):
65 path = self._sqlite_encode_path(path)
66 cached = self.storage.select("SELECT value FROM cache_{0} WHERE "
67 "path = ? AND time >= ?".format(
68 cache_type), (path, exp))
72 return True, self._sqlite_decode(cached[0])
74 def hascache(self, cache_type, path):
75 path = self._sqlite_encode_path(path)
76 return self.storage.select("SELECT value FROM cache_{0} WHERE "
77 "path = ?".format(cache_type),
80 def reset_expired_cache(self, cache_type, exp):
81 self.storage.execute("DELETE FROM cache_{0} WHERE time < ?".format(
84 def reset_all_cache(self, cache_type):
85 self.storage.execute("DELETE FROM cache_{0}".format(cache_type))
87 def get_cached(self, cache_type, context):
88 """return all values in a dictionary
89 example: {'path1': ('value1', 'time1'), 'path2': ('value2', 'time2')}
92 for path, value, time in self.storage.select("SELECT * FROM cache_{0}"
93 "".format(cache_type),
95 path = self._sqlite_decode_path(path)
96 value = self._sqlite_decode(value)
97 ret[path] = (value, time)