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