comparison wikked/cache.py @ 0:c946f4facfa2

Initial commit.
author Ludovic Chabant <ludovic@chabant.com>
date Mon, 10 Dec 2012 22:40:52 -0800
parents
children ef9cf617d76f
comparison
equal deleted inserted replaced
-1:000000000000 0:c946f4facfa2
1 import os
2 import os.path
3
4 try:
5 import simplejson as json
6 except ImportError:
7 import json
8
9
10 class Cache(object):
11 def __init__(self, root):
12 self.cache_dir = root
13
14 def read(self, url, time):
15 path, valid = self._getCachePathAndValidity(url, time)
16 if valid:
17 with open(path, 'r') as f:
18 return json.load(f)
19 return None
20
21 def write(self, url, data):
22 path = self._getCachePath(url)
23 if not os.path.isdir(os.path.dirname(path)):
24 os.makedirs(os.path.dirname(path))
25 with open(path, 'w') as f:
26 json.dump(data, f)
27
28 def remove(self, url):
29 path = self._getCachePath(url)
30 if os.path.isfile(path):
31 os.remove(path)
32
33 def getTime(self, url):
34 path = self._getCachePath(url)
35 if not os.path.isfile(path):
36 return None
37 return os.path.getmtime(path)
38
39 def _getCachePath(self, url):
40 return os.path.join(self.cache_dir, url)
41
42 def _getCachePathAndValidity(self, url, time):
43 cache_path = self._getCachePath(url)
44 if not os.path.isfile(cache_path):
45 return cache_path, False
46
47 if time >= os.path.getmtime(cache_path):
48 return cache_path, False
49
50 return cache_path, True
51