show restart notification after db update
[pywienerlinien] / gotovienna / cache.py
1 from __future__ import with_statement
2 from os import path
3 try:
4     import json
5 except ImportError:
6     import simplejson as json
7 import shutil
8 import defaults
9 import realtime
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 class Lines(dict):
31     def __init__(self):
32         self.load()
33
34     def __setitem__(self, *args, **kwargs):
35         s = dict.__setitem__(self, *args, **kwargs)
36         self.save()
37         return s
38
39     def save(self):
40         with open(defaults.cache_lines, 'w') as fp:
41             json.dump(self, fp)
42
43     def load(self):
44         l = load(defaults.cache_lines, dict)
45         if l:
46             self.update(l)
47
48 lines = Lines()
49
50 class Stations(dict):
51     stations = None
52
53     def __init__(self, line):
54         """ loads cache files
55         behaves as dict of directions/stations of line
56         automatically saves cache on updates
57         """
58         if Stations.stations == None:
59             Stations.load()
60
61         self.current_line = line
62         if line in Stations.stations:
63             self.update(Stations.stations[line])
64         # FIXME maybe cause problems in the future, race conditions
65         Stations.stations[line] = self
66
67     def __setitem__(self, *args, **kwargs):
68         u = dict.__setitem__(self, *args, **kwargs)
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 = {}