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