fixed caching classes
[pywienerlinien] / gotovienna / cache.py
1 from os import path
2 import json
3 import shutil
4 import defaults
5 import realtime
6
7
8 def load(p, typ):
9     if path.exists(p):
10         try:
11             with open(p, 'r') as f:
12                 j = json.load(f)
13                 if type(j) == typ:
14                     return j
15                 else:
16                     print 'Unexpected content in cache file'
17                     print 'rebuilding cache'
18                     shutil.copy(p, p + '.bak')
19         except ValueError:
20             # FIXME check if empty
21             print 'Corrupt cache file'
22             print 'rebuilding cache'
23             shutil.copy(p, p + '.bak')
24
25     return None
26
27
28 class Lines(dict):
29     def __init__(self):
30         self.load()
31
32     def update(self, *args, **kwargs):
33         a = dict.update(self, *args, **kwargs)
34         self.save()
35         return a
36
37     def save(self):
38         with open(defaults.cache_lines, 'w') as fp:
39             json.dump(self, fp)
40
41     def load(self):
42         l = load(defaults.cache_lines, dict)
43         if l:
44             self.update(l)
45
46 lines = Lines()
47
48
49 class Stations(dict):
50     stations = None
51
52     def __init__(self, line):
53         """ loads cache files
54         behaves as dict of directions/stations of line
55         automatically saves cache on updates
56         """
57         if Stations.stations == None:
58             Stations.load()
59
60         self.current_line = line
61         if line in Stations.stations:
62             self.update(Stations.stations[line])
63         # FIXME maybe cause problems in the future, race conditions
64         Stations.stations[line] = self
65
66     def update(self, *args, **kwargs):
67         u = dict.update(self, *args, **kwargs)
68         if args[0]:
69             Stations.save()
70         return u
71
72     @classmethod
73     def save(cls):
74         with open(defaults.cache_stations, 'w') as fp:
75             json.dump(Stations.stations, fp)
76
77     @classmethod
78     def load(cls):
79         s = load(defaults.cache_stations, dict)
80         if s:
81             cls.stations = s
82         else:
83             cls.stations = {}