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