datastore/xml: handle entire file save and be closer with new nemubot XML API

This commit is contained in:
nemunaire 2017-07-28 06:55:17 +02:00
parent c8afa65dcb
commit 76bea2bc15
2 changed files with 14 additions and 23 deletions

View File

@ -143,4 +143,15 @@ class XML(Abstract):
if self.rotate:
self._rotate(path)
return data.save(path)
import tempfile
_, tmpath = tempfile.mkstemp()
with open(tmpath, "w") as f:
import xml.sax.saxutils
gen = xml.sax.saxutils.XMLGenerator(f, "utf-8")
gen.startDocument()
data.saveElement(gen)
gen.endDocument()
# Atomic save
import shutil
shutil.move(tmpath, path)

View File

@ -196,7 +196,7 @@ class ModuleState:
if self.index_fieldname is not None:
self.setIndex(self.index_fieldname, self.index_tagname)
def save_node(self, gen):
def saveElement(self, gen):
"""Serialize this node as a XML node"""
from datetime import datetime
attribs = {}
@ -215,29 +215,9 @@ class ModuleState:
gen.startElement(self.name, attrs)
for child in self.childs:
child.save_node(gen)
child.saveElement(gen)
gen.endElement(self.name)
except:
logger.exception("Error occured when saving the following "
"XML node: %s with %s", self.name, attrs)
def save(self, filename):
"""Save the current node as root node in a XML file
Argument:
filename -- location of the file to create/erase
"""
import tempfile
_, tmpath = tempfile.mkstemp()
with open(tmpath, "w") as f:
import xml.sax.saxutils
gen = xml.sax.saxutils.XMLGenerator(f, "utf-8")
gen.startDocument()
self.save_node(gen)
gen.endDocument()
# Atomic save
import shutil
shutil.move(tmpath, filename)