From 06910d2dbd3924e70f36bb298a1331888c2a6db8 Mon Sep 17 00:00:00 2001 From: Tony Mack Date: Sat, 14 Mar 2009 20:58:49 +0000 Subject: [PATCH] added XmlStorage class --- geni/util/storage.py | 51 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 7 deletions(-) diff --git a/geni/util/storage.py b/geni/util/storage.py index 50f13581..bd523510 100644 --- a/geni/util/storage.py +++ b/geni/util/storage.py @@ -1,15 +1,16 @@ import os +from geni.util.rspec import RecordSpec class SimpleStorage(dict): - + """ + Handles storing and loading python dictionaries. The storage file created + is a string representation of the native python dictionary. + """ db_filename = None - types = ['dict', 'tabbed', 'text', 'shell'] - - def __init__(self, db_filename, db = {}, type = 'dict'): + type = 'dict' + + def __init__(self, db_filename, db = {}): - if type not in self.types: - raise Exception, "Invalid type %s, must be in %s" % (type, self.types) - self.type = type dict.__init__(self, db) self.db_filename = db_filename @@ -22,6 +23,7 @@ class SimpleStorage(dict): % self.db_filename else: self.write() + self.load() def write(self): db_file = open(self.db_filename, 'w') @@ -30,3 +32,38 @@ class SimpleStorage(dict): def sync(self): self.write() + +class XmlStorage(SimpleStorage): + """ + Handles storing and loading python dictionaries. The storage file created + is a xml representation of the python dictionary. + """ + db_filename = None + type = 'xml' + + def load(self): + """ + Parse an xml file and store it as a dict + """ + data = RecordSpec() + if os.path.exists(self.db_filename) and os.path.isfile(self.db_filename): + data.parseFile(self.db_filename) + dict.__init__(self, data.toDict()) + elif os.path.exists(self.db_filename) and not os.path.isfile(self.db_filename): + raise IOError, '%s exists but is not a file. please remove it and try again' \ + % self.db_filename + else: + self.write() + self.load() + + def write(self): + data = RecordSpec() + data.parseDict(self) + db_file = open(self.db_filename, 'w') + db_file.write(data.toprettyxml()) + db_file.close() + + def sync(self): + self.write() + + -- 2.43.0