use self.get_auth_info
[sfa.git] / sfa / util / storage.py
1 ### $Id$
2 ### $URL$
3
4 import os
5
6 from sfa.util.rspec import RecordSpec
7
8 class SimpleStorage(dict):
9     """
10     Handles storing and loading python dictionaries. The storage file created
11     is a string representation of the native python dictionary.
12     """
13     db_filename = None
14     type = 'dict'
15     
16     def __init__(self, db_filename, db = {}):
17
18         dict.__init__(self, db)
19         self.db_filename = db_filename
20     
21     def load(self):
22         if os.path.exists(self.db_filename) and os.path.isfile(self.db_filename):
23             db_file = open(self.db_filename, 'r')
24             dict.__init__(self, eval(db_file.read()))
25         elif os.path.exists(self.db_filename) and not os.path.isfile(self.db_filename):
26             raise IOError, '%s exists but is not a file. please remove it and try again' \
27                            % self.db_filename
28         else:
29             self.write()
30             self.load()
31  
32     def write(self):
33         db_file = open(self.db_filename, 'w')  
34         db_file.write(str(self))
35         db_file.close()
36     
37     def sync(self):
38         self.write()
39
40 class XmlStorage(SimpleStorage):
41     """
42     Handles storing and loading python dictionaries. The storage file created
43     is a xml representation of the python dictionary.
44     """ 
45     db_filename = None
46     type = 'xml'
47
48     def load(self):
49         """
50         Parse an xml file and store it as a dict
51         """ 
52         data = RecordSpec()
53         if os.path.exists(self.db_filename) and os.path.isfile(self.db_filename):
54             data.parseFile(self.db_filename)
55             dict.__init__(self, data.toDict())
56         elif os.path.exists(self.db_filename) and not os.path.isfile(self.db_filename):
57             raise IOError, '%s exists but is not a file. please remove it and try again' \
58                            % self.db_filename
59         else:
60             self.write()
61             self.load()
62
63     def write(self):
64         data = RecordSpec()
65         data.parseDict(self)
66         db_file = open(self.db_filename, 'w')
67         db_file.write(data.toprettyxml())
68         db_file.close()
69
70     def sync(self):
71         self.write()
72
73