minor updates
[sfa.git] / geni / util / storage.py
1 import os
2
3 class SimpleStorage(dict):
4
5     db_filename = None
6     types = ['dict', 'tabbed', 'text', 'shell']
7
8     def __init__(self, db_filename, db = {}, type = 'dict'):
9
10         if type not in self.types:
11             raise Exception, "Invalid type %s, must be in %s" % (type, self.types)
12         self.type = type
13         dict.__init__(self, db)
14         self.db_filename = db_filename
15     
16     def load(self):
17         if os.path.exists(self.db_filename) and os.path.isfile(self.db_filename):
18             db_file = open(self.db_filename, 'r')
19             dict.__init__(self, eval(db_file.read()))
20         elif os.path.exists(self.db_filename) and not os.path.isfile(self.db_filename):
21             raise IOError, '%s exists but is not a file. please remove it and try again' \
22                            % self.db_filename
23         else:
24             self.write()
25  
26     def write(self):
27         db_file = open(self.db_filename, 'w')  
28         db_file.write(str(self))
29         db_file.close()
30     
31     def sync(self):
32         self.write()