bd5235107728c6b659091a645c1b6b5462f61f0b
[sfa.git] / geni / util / storage.py
1 import os
2 from geni.util.rspec import RecordSpec
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 = {}):
13
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         data = RecordSpec()
49         if os.path.exists(self.db_filename) and os.path.isfile(self.db_filename):
50             data.parseFile(self.db_filename)
51             dict.__init__(self, data.toDict())
52         elif os.path.exists(self.db_filename) and not os.path.isfile(self.db_filename):
53             raise IOError, '%s exists but is not a file. please remove it and try again' \
54                            % self.db_filename
55         else:
56             self.write()
57             self.load()
58
59     def write(self):
60         data = RecordSpec()
61         data.parseDict(self)
62         db_file = open(self.db_filename, 'w')
63         db_file.write(data.toprettyxml())
64         db_file.close()
65
66     def sync(self):
67         self.write()
68
69