9033434f6cf8d146df5d147a29a2e147db0b5895
[sfa.git] / sfa / util / storage.py
1 import os
2 from sfa.util.xml import XML
3
4 class SimpleStorage(dict):
5     """
6     Handles storing and loading python dictionaries. The storage file created
7     is a string representation of the native python dictionary.
8     """
9     db_filename = None
10     type = 'dict'
11     
12     def __init__(self, db_filename, db = None):
13         if db is None: db={}
14         dict.__init__(self, db)
15         self.db_filename = db_filename
16     
17     def load(self):
18         if os.path.exists(self.db_filename) and os.path.isfile(self.db_filename):
19             db_file = open(self.db_filename, 'r')
20             dict.__init__(self, eval(db_file.read()))
21         elif os.path.exists(self.db_filename) and not os.path.isfile(self.db_filename):
22             raise IOError('%s exists but is not a file. please remove it and try again' \
23                            % self.db_filename)
24         else:
25             self.write()
26             self.load()
27  
28     def write(self):
29         db_file = open(self.db_filename, 'w')  
30         db_file.write(str(self))
31         db_file.close()
32     
33     def sync(self):
34         self.write()
35
36 class XmlStorage(SimpleStorage):
37     """
38     Handles storing and loading python dictionaries. The storage file created
39     is a xml representation of the python dictionary.
40     """ 
41     db_filename = None
42     type = 'xml'
43
44     def load(self):
45         """
46         Parse an xml file and store it as a dict
47         """ 
48         if os.path.exists(self.db_filename) and os.path.isfile(self.db_filename):
49             xml = XML(self.db_filename)
50             dict.__init__(self, xml.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         xml = XML()
60         xml.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