def _validate_tox_config_sections(self): if not self.config_parser.sections(): raise NoSectionError("Bad Config. No sections found.") if all(section not in SECTIONS for section in self.config_parser.sections()): raise NoSectionError("File doesn't contain required sections")
def get(self, sec, opt, raw=False, vars=None): if vars is None: vars = {} try: return self._cfg.get(sec, opt, raw=raw, vars=vars) except AttributeError: raise NoSectionError(sec)
def _unify_values(self, section, variables): """Create a sequence of lookups with 'variables' taking priority over the 'section' which takes priority over the DEFAULTSECT. """ try: sectiondict = self._sections[section] except KeyError: if section != self.default_section: raise NoSectionError(section) else: sectiondict = {} # Update with the entry specific variables vardict = {} if variables: for key, value in variables.items(): if value is not None: value = str(value) vardict[self.optionxform(key)] = value prefix = section.split(".", 1)[0] + ".DEFAULT" # print("searched for {0}".format(prefix)) try: defaultdict = self._sections[prefix] return _ChainMap(vardict, sectiondict, defaultdict, self._defaults) except KeyError: return _ChainMap(vardict, sectiondict, self._defaults)
def get(self, section, option, raw=False, vars=None, fallback=_UNSET): d = self._defaults.copy() try: d.update(self._sections[section]) except KeyError: if section != DEFAULTSECT: raise NoSectionError(section) # Update the entry specific variables if vars: for key, value in vars.items(): d[self.optionxform(key)] = value option = self.optionxform(option) try: value = d[option] except KeyError: if fallback is _UNSET: raise NoOptionError(option, section) else: return fallback if raw or value is None: return value else: return self._interpolate(section, option, value, d)
def _get_section_option(self, section_option): """splits ``section_option`` (section.option) in two parts and returns them as list ``[section, option]``, if: * it likes the format of ``section_option`` * the ``section`` is known * the ``option`` is known Else one of the following exceptions will be thrown: * `BadOptionError` * `NoSectionError` * `NoOptionError` """ sect_opt = section_option.lower().split(".") # TODO: cache it if len(sect_opt) != 2 or not sect_opt[0] or not sect_opt[1]: raise BadOptionError( _("Bad format: '%s' - expected: " "section.option") % get_unicode(section_option)) if not sect_opt[0] in self._cfg: raise NoSectionError(sect_opt[0]) if not sect_opt[1] in self._cfg[sect_opt[0]]: raise NoOptionError(sect_opt[1], sect_opt[0]) return sect_opt
def verify_required_options(section, option_keys, defaults={}, parse_env=False): """ Verifies that section exists, and that it has option_keys defined :param str section: Section in the config :param list[str] option_keys: list of required options :param dict[str, str] defaults: dict of default option values :param bool parse_env: parse environment variables (trumps file options) :rtype: dict[str, str|int|float|bool] :raises: NoSectionError, NoOptionError """ merged_config = ConfigSection(defaults) file_config = read_config() if section in file_config: for k, v in file_config[section].items(): merged_config[k] = _parse_option(v) if parse_env: up_sec = section.upper().replace(' ', '_') for k, v in merged_config.items(): candidate = environ.get('{}_{}'.format(up_sec, k.upper())) if candidate is not None: merged_config[k] = _parse_option(candidate) missing_requireds = [ k for k in option_keys if k not in merged_config or merged_config[k] is None ] if missing_requireds: if section not in file_config: raise NoSectionError(section) else: raise NoOptionError(', '.join(missing_requireds), section) return merged_config
def has_option(self, section, option): """Check for the existence of a given option in a given section.""" if section in self.data: sec = self.data[section] else: raise NoSectionError(section) return (option in sec)
def __find_section(self, domain): l = self.sections() for section in iter(l): if section.lower() == domain.lower(): return section raise NoSectionError(domain)
def items(self, section, raw=False, vars=None): """Return a list of tuples with (name, value) for each option in the section. All % interpolations are expanded in the return values, based on the defaults passed into the constructor, unless the optional argument `raw' is true. Additional substitutions may be provided using the `vars' argument, which must be a dictionary whose contents overrides any pre-existing defaults. The section DEFAULT is special. """ if section != DEFAULTSECT and not self.has_section(section): raise NoSectionError(section) if vars is None: options = list(self.data[section]) else: options = [] for x in self.data[section]: if x not in vars: options.append(x) options.extend(list(vars.keys())) if "__name__" in options: options.remove("__name__") d = ConfigDict(self, section, vars) if raw: return [(option, d[option]) for option in options] else: return [(option, self._interpolate(section, option, d[option], d)) for option in options]
def main(): """設定ファイルをparseして、slackbotを起動します 1. configparserで設定ファイルを読み込む 2. 設定ファイルに `alembic` セクションが設定されているかチェック 3. 設定ファイルの情報でDB周りの設定を初期化 4. slackbotの処理を開始 """ parser = get_argparser() args = parser.parse_args() conf = ConfigParser() conf.read_file(args.config) # 環境変数で指定したいため ini ファイルでなくここで追記 conf["alembic"]['sqlalchemy.url'] = SQLALCHEMY_URL conf["alembic"]['sqlalchemy.echo'] = SQLALCHEMY_ECHO if SQLALCHEMY_POOL_SIZE: conf["alembic"]['sqlalchemy.pool_size'] = SQLALCHEMY_POOL_SIZE if not conf.has_section('alembic'): raise NoSectionError('alembic') init_dbsession(conf['alembic']) bot = Bot() bot.run()
def get_section(self, section, createIfNone=False): if not self.has_section(section): if createIfNone: self.add_section(section) else: raise NoSectionError("No such section %s" % section) return ConfigSection(self, section)
def options(self, section, no_defaults=False, **kwargs): if no_defaults: try: return list(self._sections[section].keys()) except KeyError: raise NoSectionError(section) else: return super().options(section, **kwargs)
def items(self, section): if section in self.data: ans = [] for opt in self.data[section]: ans.append((opt, self.get(section, opt))) return ans else: raise NoSectionError(section)
def options(self, section, exclude_default=True, **kwargs): if exclude_default: try: return list(self._sections[section].keys()) except KeyError: raise NoSectionError(section) else: return super().options(section, **kwargs)
def _checkConfigurationFile(self): for section in self.required.keys(): if not self.parser.has_section(section): raise NoSectionError(section) for option in self.required.get(section): if not self.parser.has_option(section, option): raise NoOptionError(option, section)
def items(self, section): try: ans = [] for opt in self.data[section]: ans.append((opt, self.get(section, opt))) return ans except KeyError: raise NoSectionError(section)
def test_load_fail_no_section(self, cfgparser_mock): node = dut.DucoNode(111, 222) cfgparser_mock_object = MagicMock(spec=dut.ConfigParser) cfgparser_mock_object.get.side_effect = NoSectionError( 'some message for missing config parser section') node._load(cfgparser_mock_object) self.assertEqual(int(node.number), 111) self.assertEqual(int(node.address), 222) self.assertEqual(node.blacklist, False)
def getint(self, section, option, check_default=True, **kws): if self.has_option(section, option, False): return ConfigParser.getint(self, section, option, **kws) elif check_default and self.has_default(option): return self.getint_default(option, **kws) elif not self.has_section(section): raise NoSectionError(section) else: raise NoOptionError(option, section)
def options(self, section, withDefault=False): """Return a list of option names for the given section name. Parameter `withDefault` controls the include of names from section `[DEFAULT]` """ try: return self._cfg.options(section, withDefault) except AttributeError: raise NoSectionError(section)
def as_dict(self, section): d = self._defaults.copy() try: d.update(self._sections[section]) except KeyError: if section != "DEFAULT": raise NoSectionError(section) return d
def options(self, section): # Order [DEFAULT] options before section options; the default # implementation orders them after. options = self._defaults.copy() try: options.update(self._sections[section]) except KeyError: raise_from(NoSectionError(section), None) return list(options.keys())
def _read_value(parser, section, option): if not parser.has_section(section): raise NoSectionError("%s (available sections: %s)" % (section, sorted(parser.sections()))) if not parser.has_option(section, option): raise NoOptionError( "%s (available options: %s)" % (option, sorted(parser.options(section))), section) else: return parser.get(section, option)
def test_load_conf_from_default_path_with_invalid_section(self, ConfigParserGetItemMocked, logger_mocked): from configparser import NoSectionError filepath = '/path/to/config/file.ini' ConfigParserGetItemMocked.side_effect = NoSectionError('') assert len(load_conf_from_file(filepath, section='invalidsection')) == 0 logger_mocked.warn.assert_called_once_with( "Couldn't find \"invalidsection\" section in \"/path/to/config/file.ini\"" )
def get(self, section, option, vars=None): if not self.has_section(section): raise NoSectionError(section) if vars is not None and option in vars: value = vars[option] try: sec = self.data[section] return sec._compat_get(option) except KeyError: raise NoOptionError(option, section)
def options(self, section): # Order [DEFAULT] options before section options; the default # implementation orders them after. options = list(self._defaults.keys()) try: section = self._sections[section] except KeyError: raise_from(NoSectionError(section), None) options.extend(k for k in section.keys() if k not in self._defaults) return options
def options(self, section: str) -> List[str]: """ Returns list of configuration options for the given section. :param section: """ if section not in self: raise NoSectionError(section) from None return self[section].options()
def from_file(cls, filename): conf = SiteConfig() if not conf.read([filename]): raise ParsingError("Failed to parse file: %s" % filename) # Check sections for section in cls.required_sections: if not conf.has_section(section): raise NoSectionError("Missing section: %s" % section) return conf
def remove_option(self, section, option): """Remove an option.""" if section in self.data: sec = self.data[section] else: raise NoSectionError(section) if option in sec: del sec[option] return 1 else: return 0
def get(self, section, option, vars=None): if not self.has_section(section): raise NoSectionError(section) if vars is not None and option in vars: value = vars[option] sec = self.data[section] if option in sec: return sec._compat_get(option) else: raise NoOptionError(option, section)
def has_option(self, section, option): """Check for the existence of a given option in a given section.""" try: sec = self.data[section] except KeyError: raise NoSectionError(section) try: sec[option] return True except KeyError: return False