comparison engine/python/fife/extensions/serializers/simplexml.py @ 569:466d76db9701

Some small code cleanups in the extensions. The SimpleXMLSerializer now makes use of exceptions.
author prock@33b003aa-7bff-0310-803a-e67f0ece8222
date Mon, 28 Jun 2010 19:28:53 +0000
parents bfbf329e1da8
children 0bbe6e8ad9c8
comparison
equal deleted inserted replaced
568:bfbf329e1da8 569:466d76db9701
21 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 21 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 # #################################################################### 22 # ####################################################################
23 23
24 import os 24 import os
25 from StringIO import StringIO 25 from StringIO import StringIO
26 26
27 try: 27 from fife.extensions.serializers import ET, SerializerError, InvalidFormat, NotFound
28 import xml.etree.cElementTree as ET
29 except:
30 import xml.etree.ElementTree as ET
31 28
32 29
33 EMPTY_XML_FILE="""\ 30 EMPTY_XML_FILE="""\
34 <?xml version='1.0' encoding='UTF-8'?> 31 <?xml version='1.0' encoding='UTF-8'?>
35 <Settings> 32 <Settings>
57 54
58 def load(self, filename=None): 55 def load(self, filename=None):
59 """ 56 """
60 Loads the XML file into memory and validates it. 57 Loads the XML file into memory and validates it.
61 58
59 Raises a SerializerError exception if the file is not specified.
60
62 @note: If the file does not exist it will automatically create a blank file for you. 61 @note: If the file does not exist it will automatically create a blank file for you.
63 """ 62 """
64 if filename: 63 if filename:
65 self._file = filename 64 self._file = filename
66 65
67 if not self._file: 66 if not self._file:
68 print "Cannot load file. No filename specified!" 67 raise SerializerError("Cannot load file or create file. No filename specified!")
69 return
70 68
71 if not os.path.exists(self._file): 69 if not os.path.exists(self._file):
72 self._tree = ET.parse(StringIO(EMPTY_XML_FILE)) 70 self._tree = ET.parse(StringIO(EMPTY_XML_FILE))
73 self._tree.write(self._file, 'UTF-8') 71 self._tree.write(self._file, 'UTF-8')
74 else: 72 else:
87 savefile = filename 85 savefile = filename
88 else: 86 else:
89 savefile = self._file 87 savefile = self._file
90 88
91 if not savefile: 89 if not savefile:
92 print "Cannot save file. No filename specified!" 90 raise SerializerError("Cannot save file. No filename specified!")
93 return
94 91
95 """ Writes the settings to file """ 92 """ Writes the settings to file """
96 self._indent(self._root_element) 93 self._indent(self._root_element)
97 self._tree.write(savefile, 'UTF-8') 94 self._tree.write(savefile, 'UTF-8')
98 95
164 @type value: C{str} or C{unicode} or C{int} or C{float} or C{bool} or C{list} or C{dict} 161 @type value: C{str} or C{unicode} or C{int} or C{float} or C{bool} or C{list} or C{dict}
165 @param extra_attrs: Extra attributes to be stored in the XML-file 162 @param extra_attrs: Extra attributes to be stored in the XML-file
166 @type extra_attrs: C{dict} 163 @type extra_attrs: C{dict}
167 """ 164 """
168 if not isinstance(name, str) and not isinstance(name, unicode): 165 if not isinstance(name, str) and not isinstance(name, unicode):
169 raise AttributeError("Settings:set: Invalid type for name argument.") 166 raise AttributeError("SimpleXMLSerializer.set(): Invalid type for name argument.")
170 167
171 moduleTree = self._getModuleTree(module) 168 moduleTree = self._getModuleTree(module)
172 e_type = "str" 169 e_type = "str"
173 170
174 if isinstance(value, bool): # This must be before int 171 if isinstance(value, bool): # This must be before int
205 attrs[k] = extra_args[k] 202 attrs[k] = extra_args[k]
206 elm = ET.SubElement(moduleTree, "Setting", attrs) 203 elm = ET.SubElement(moduleTree, "Setting", attrs)
207 elm.text = value 204 elm.text = value
208 205
209 def _validateTree(self): 206 def _validateTree(self):
210 """ Iterates the XML tree and prints warning when an invalid tag is found """ 207 """
208 Iterates the XML tree and prints warning when an invalid tag is found.
209
210 Raises an InvalidFormat exception if there is a format error.
211 """
211 for c in self._root_element.getchildren(): 212 for c in self._root_element.getchildren():
212 if c.tag != "Module": 213 if c.tag != "Module":
213 print "Invalid tag in " + self._file + ". Expected Module, got: ", c.tag 214 raise InvalidFormat("Invalid tag in " + self._file + ". Expected Module, got: " + c.tag)
214 elif c.get("name", "") == "": 215 elif c.get("name", "") == "":
215 print "Invalid tag in " + self._file + ". Module name is empty." 216 raise InvalidFormat("Invalid tag in " + self._file + ". Module name is empty.")
216 else: 217 else:
217 for e in c.getchildren(): 218 for e in c.getchildren():
218 if e.tag != "Setting": 219 if e.tag != "Setting":
219 print "Invalid tag in " + self._file + " in module: ",c.tag, 220 raise InvalidFormat("Invalid tag in " + self._file + " in module: " + c.tag + ". Expected Setting, got: " + e.tag)
220 print ". Expected Setting, got: ", e.tag
221 elif c.get("name", "") == "": 221 elif c.get("name", "") == "":
222 print "Invalid tag in " + self._file + " in module: ",c.tag, 222 raise InvalidFormat("Invalid tag in " + self._file + " in module: " + c.tag + ". Setting name is empty" + e.tag)
223 print ". Setting name is empty", e.tag
224 223
225 def _getModuleTree(self, module): 224 def _getModuleTree(self, module):
226 """ 225 """
227 Returns a module element from the XML tree. If no module with the specified 226 Returns a module element from the XML tree. If no module with the specified
228 name exists, a new element will be created. 227 name exists, a new element will be created.