From 101bff5ef5fec6382ab572a286c4e79d0312c6cd Mon Sep 17 00:00:00 2001 From: Matthijs Kooijman Date: Fri, 6 Aug 2010 18:24:14 +0200 Subject: [PATCH] Action: Add config accessor functions. These convenience functions allow for accessing configuration values either allowing them to be unset (and return None) or mandatory (and throw an appropriate exception). By default, ConfigParser throws an exception with a less appropriate exception. --- src/lib/backupninja/config.py | 9 ++++++++ src/lib/backupninja/handlers/__init__.py | 29 ++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/lib/backupninja/config.py b/src/lib/backupninja/config.py index 030fc57..5f1b283 100644 --- a/src/lib/backupninja/config.py +++ b/src/lib/backupninja/config.py @@ -28,6 +28,15 @@ default_global_config = {} import logging as log +class ConfigError(Exception): + """ + An exception thrown when something is wrong with the config. + This is not thrown by the config module, but it is meant to be + thrown by handlers when they find something wrong with the + configuration contents. + """ + pass + def get_global_config(opts): """ Returns the global configuration, in a SafeConfigParser object. diff --git a/src/lib/backupninja/handlers/__init__.py b/src/lib/backupninja/handlers/__init__.py index 72b3017..f6559f9 100644 --- a/src/lib/backupninja/handlers/__init__.py +++ b/src/lib/backupninja/handlers/__init__.py @@ -19,7 +19,7 @@ """ Action superclass with common functionality """ -import sys +import sys, ConfigParser import logging as log from backupninja import config @@ -59,7 +59,32 @@ class Action(object): """ self.conf = config.load_config(filename, self.default_config) - + def get_config_optional(self, section, option): + """ + Returns the value of the given option. If the option was not set + (and no default was set in self.default_config), return None. + + This is a convenience wrapper for ConfigParser.get(), since that + throws an exception on unset options. + """ + try: + return self.conf.get(section, option) + except ConfigParser.NoOptionError: + return None + + def get_config_mandatory(self, section, option): + """ + Returns the value of the given option. If the option was not set + (and no default was set in self.default_config), raises a + backupninja.config.ConfigError. + + This is a convenience wrapper for ConfigParser.get(), since that + has a very generic exception message on unknown options. + """ + try: + return self.conf.get(section, option) + except ConfigParser.NoOptionError: + raise config.ConfigError("Option '%s' in section '%s' is mandatory, please configure it" % (option, section)) def create_action(ty): """ -- 2.30.2