5d915398efc6df679733afd8181f811853b63f35
[sfa.git] / sfa / util / storage.py
1 import os
2
3 from sfa.util.rspec import RecordSpec
4
5 class SimpleStorage(dict):
6     """
7     Handles storing and loading python dictionaries. The storage file created
8     is a string representation of the native python dictionary.
9     """
10     db_filename = None
11     type = 'dict'
12     
13     def __init__(self, db_filename, db = {}):
14
15         dict.__init__(self, db)
16         self.db_filename = db_filename
17     
18     def load(self):
19         if os.path.exists(self.db_filename) and os.path.isfile(self.db_filename):
20             db_file = open(self.db_filename, 'r')
21             dict.__init__(self, eval(db_file.read()))
22         elif os.path.exists(self.db_filename) and not os.path.isfile(self.db_filename):
23             raise IOError, '%s exists but is not a file. please remove it and try again' \
24                            % self.db_filename
25         else:
26             self.write()
27             self.load()
28  
29     def write(self):
30         db_file = open(self.db_filename, 'w')  
31         db_file.write(str(self))
32         db_file.close()
33     
34     def sync(self):
35         self.write()
36
37 class XmlStorage(SimpleStorage):
38     """
39     Handles storing and loading python dictionaries. The storage file created
40     is a xml representation of the python dictionary.
41     """ 
42     db_filename = None
43     type = 'xml'
44
45     def load(self):
46         """
47         Parse an xml file and store it as a dict
48         """ 
49         data = RecordSpec()
50         if os.path.exists(self.db_filename) and os.path.isfile(self.db_filename):
51             data.parseFile(self.db_filename)
52             dict.__init__(self, data.toDict())
53         elif os.path.exists(self.db_filename) and not os.path.isfile(self.db_filename):
54             raise IOError, '%s exists but is not a file. please remove it and try again' \
55                            % self.db_filename
56         else:
57             self.write()
58             self.load()
59
60     def write(self):
61         data = RecordSpec()
62         data.parseDict(self)
63         db_file = open(self.db_filename, 'w')
64         db_file.write(data.toprettyxml())
65         db_file.close()
66
67     def sync(self):
68         self.write()
69
70