Author: justi9
Date: 2008-10-01 11:11:54 -0400 (Wed, 01 Oct 2008)
New Revision: 2558
Added:
mgmt/trunk/parsley/python/parsley/config.py
Log:
Add a common config api to parsley
Added: mgmt/trunk/parsley/python/parsley/config.py
===================================================================
--- mgmt/trunk/parsley/python/parsley/config.py (rev 0)
+++ mgmt/trunk/parsley/python/parsley/config.py 2008-10-01 15:11:54 UTC (rev 2558)
@@ -0,0 +1,76 @@
+import logging
+
+from ConfigParser import SafeConfigParser
+
+log = logging.getLogger("parsley.config")
+
+class Config(object):
+ def __init__(self):
+ self._params = list()
+ self._params_by_name = dict()
+
+ def init(self):
+ for param in self._params:
+ param.init()
+
+ def load_file(self, file):
+ conf = SafeConfigParser()
+ found = conf.read(file)
+
+ if found:
+ log.info("Read config file '%s'" % file)
+ else:
+ log.info("Config file '%s' not found" % file)
+
+ params = dict()
+
+ if (conf.has_section("main")):
+ for key, value in conf.items("main"):
+ params[key] = value
+
+ self.load_dict(params)
+
+ def load_dict(self, params):
+ for sname, svalue in params.items():
+ param = self._params_by_name.get(sname)
+
+ if param:
+ name = param.name.replace("-", "_")
+ value = param.unmarshal(svalue)
+
+ setattr(self, name, value)
+
+ else:
+ log.info("Ignoring unrecognized parameter '%s'" %
sname)
+
+ def prt(self):
+ print "Configuration:"
+
+ for param in self._params:
+ value = getattr(self, param.name.replace("-", "_"))
+
+ if value == param.default:
+ flag = " [default]"
+ else:
+ flag = ""
+
+ print " %s = %s%s" % (param.name, value, flag)
+
+class ConfigParameter(object):
+ def __init__(self, config, name, type):
+ self.config = config
+ self.name = name
+ self.type = type
+ self.default = None
+
+ self.config._params.append(self)
+ self.config._params_by_name[self.name] = self
+
+ def init(self):
+ if hasattr(self.config, self.name):
+ raise Exception("Parameter '%s' already present" %
self.name)
+
+ setattr(self.config, self.name.replace("-", "_"),
self.default)
+
+ def unmarshal(self, string):
+ return self.type(string)
Show replies by date