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