Merge branch 'master' of ssh://git.f-lab.fr/git/sfa
[sfa.git] / sfa / util / storage.py
1 import os
2 from sfa.util.xml import XML
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         if os.path.exists(self.db_filename) and os.path.isfile(self.db_filename):
48             xml = XML(self.db_filename)
49             dict.__init__(self, xml.todict())
50         elif os.path.exists(self.db_filename) and not os.path.isfile(self.db_filename):
51             raise IOError, '%s exists but is not a file. please remove it and try again' \
52                            % self.db_filename
53         else:
54             self.write()
55             self.load()
56
57     def write(self):
58         xml = XML()
59         xml.parseDict(self)
60         db_file = open(self.db_filename, 'w')
61         db_file.write(data.toprettyxml())
62         db_file.close()
63
64     def sync(self):
65         self.write()
66
67