started with 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(path):
9     if path.exists(path, typ):
10         try:
11             with open(path, '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(path, path + '.bak')
19         except ValueError:
20             print 'Corrupt cache file'
21             print 'rebuilding cache'
22             shutil.copy(path, path + '.bak')
23
24     return None
25
26 class Lines(list):
27     def __init__(self, lines=[]):
28         l = load(defaults.cache_line)
29         if l and type(l) == list:
30             lines = l
31         self.lines = lines
32
33     def __iter__(self):
34         for line in self.lines:
35             yield line
36         raise StopIteration()
37
38     def __iadd__(self, y):
39         self.lines += y
40
41     def __add__(self, y):
42         return self.lines + y
43
44     def __getitem__(self, y):
45         return self.lines[y]
46
47     def __len__(self):
48         return len(self.lines)
49
50     def __str__(self):
51         return str(self.lines)
52
53     def __setitem__(self, i, y):
54         self.lines[i] = y
55
56 class Stations(dict):
57     stations = {}
58
59     def __init__(self, line=False):
60         """ loads cache files
61         if line=False behaves as dict of all lines/stations
62         if line behaves as dict of directions/stations of line
63         """
64         if not Stations.stations:
65             s = load(defaults.cache_line, dict)
66             if s:
67                 Stations.stations = st
68
69         self.current_line = line
70         if line == False:
71             self.dict = Stations.stations
72         elif line in Stations.stations:
73             self.dict = Stations.stations[line]
74         else:
75             Stations.stations[line] = {}
76             self.dict = Stations.stations[line]
77
78
79     def __getitem__(self, *args, **kwargs):
80         return self.dict.__getitem__(self, *args, **kwargs)