Python configparser.DEFAULTSECT Examples

The following are 16 code examples of configparser.DEFAULTSECT(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module configparser , or try the search function .
Example #1
Source File: blitz.configcheck.py    From raspiblitz with MIT License 6 votes vote down vote up
def reload(self):
        """load config from file"""
        parser = ConfigParser()

        log.debug("loading config from file: {}".format(self.abs_path))
        with open(self.abs_path) as f:
            parser.read_string("[{}]\n".format(DEFAULTSECT) + f.read())

        default_s = parser[DEFAULTSECT]

        self.base_image = get_str_clean(default_s, "baseimage", self.base_image)
        self.chain = get_str_clean(default_s, "chain", self.chain)
        self.message = get_str_clean(default_s, "message", self.message)
        self.network = get_str_clean(default_s, "network", self.network)
        self.setup_step = get_int_safe(default_s, "setupStep", self.setup_step)
        self.state = get_str_clean(default_s, "state", self.state)
        self.undervoltage_reports = get_int_safe(default_s, "undervoltageReports", self.undervoltage_reports) 
Example #2
Source File: config.py    From raspiblitz with MIT License 6 votes vote down vote up
def reload(self):
        """load config from file"""
        parser = ConfigParser()

        log.debug("loading RaspiBlitzInfo config from file: {}".format(self.abs_path))
        with open(self.abs_path) as f:
            parser.read_string("[{}]\n".format(DEFAULTSECT) + f.read())

        default_s = parser[DEFAULTSECT]

        self.base_image = get_str_clean(default_s, "baseimage", self.base_image)
        self.chain = get_str_clean(default_s, "chain", self.chain)
        self.message = get_str_clean(default_s, "message", self.message)
        self.network = get_str_clean(default_s, "network", self.network)
        self.setup_step = get_int_safe(default_s, "setupStep", self.setup_step)
        self.state = get_str_clean(default_s, "state", self.state)
        self.undervoltage_reports = get_int_safe(default_s, "undervoltageReports", self.undervoltage_reports) 
Example #3
Source File: downloads.py    From ungoogled-chromium with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _parse_data(self, path):
        """
        Parses an INI file located at path

        Raises schema.SchemaError if validation fails
        """

        def _section_generator(data):
            for section in data:
                if section == configparser.DEFAULTSECT:
                    continue
                yield section, dict(
                    filter(lambda x: x[0] not in self._ini_vars, data.items(section)))

        new_data = configparser.ConfigParser(defaults=self._ini_vars)
        with path.open(encoding=ENCODING) as ini_file:
            new_data.read_file(ini_file, source=str(path))
        try:
            self._schema.validate(dict(_section_generator(new_data)))
        except schema.SchemaError as exc:
            get_logger().error('downloads.ini failed schema validation (located in %s)', path)
            raise exc
        return new_data 
Example #4
Source File: config.py    From data.world-py with Apache License 2.0 6 votes vote down vote up
def __migrate_config(legacy_file_path):
        config_parser = configparser.ConfigParser()

        with open(legacy_file_path, 'r') as legacy:
            regex = re.compile(r"^token\s*=\s*(\S.*)$")
            token = next(iter(
                [regex.match(line.strip()).group(1) for line in legacy if
                 regex.match(line)]),
                None)
            if token is not None:
                config_parser[configparser.DEFAULTSECT] = {'auth_token': token}

        # Will leave legacy in case R SDK may still need it
        # os.remove(legacy_file_path)

        return config_parser 
Example #5
Source File: config.py    From data.world-py with Apache License 2.0 6 votes vote down vote up
def __migrate_invalid_defaults(config_parser):
        # This fixes an issue related to us having referred to the default
        # section in the config file as 'default' as opposed to using
        # configparser.DEFAULTSECT
        # That may result in 'ValueError: Invalid section name: default'
        # https://github.com/datadotworld/data.world-py/issues/18
        invalid_defaults = []
        for section in config_parser.sections():
            # Doesn't include DEFAULTSECT, but checking nonetheless
            if (section != configparser.DEFAULTSECT and
                    section.lower() == configparser.DEFAULTSECT.lower()):
                invalid_defaults.append(section)

        if len(invalid_defaults) == 1:
            old_default = invalid_defaults[0]
            config_parser[configparser.DEFAULTSECT] = {
                option: config_parser.get(old_default, option)
                for option in config_parser.options(old_default)}

        for section in invalid_defaults:
            config_parser.remove_section(section)

        return len(invalid_defaults) 
Example #6
Source File: bindings.py    From citest with Apache License 2.0 6 votes vote down vote up
def __contains__(self, name):
    """Determine if a binding name is defined."""

    key = _normalize_key(name)
    if (key in self.__overrides
        or key in self.__lazy_initializers
        or key in self.__defaults
        or key in self.__config_parser.defaults()):
      return True

    all_sections = ([self.__section]
                    if self.__section
                    else self.__config_parser.sections())
    if not all_sections:
      all_sections = [ConfigParser.DEFAULTSECT]

    for section in all_sections:
      if self.__config_parser.has_option(section, key):
        return True
    return False 
Example #7
Source File: blitz.configcheck.py    From raspiblitz with MIT License 5 votes vote down vote up
def reload(self):
        """load config from file"""
        parser = ConfigParser()

        log.debug("loading config from file: {}".format(self.abs_path))
        with open(self.abs_path) as f:
            parser.read_string("[{}]\n".format(DEFAULTSECT) + f.read())

        default_s = parser[DEFAULTSECT]

        self.auto_nat_discovery = default_s.getboolean("autoNatDiscovery", self.auto_nat_discovery)
        self.auto_pilot = default_s.getboolean("autoPilot", self.auto_pilot)
        self.auto_unlock = default_s.getboolean("autoUnlock", self.auto_unlock)
        self.chain = get_str_clean(default_s, "chain", self.chain)
        self.dynDomain = get_str_clean(default_s, "dynDomain", self.dynDomain)
        self.dyn_update_url = get_str_clean(default_s, "dynUpdateUrl", self.dyn_update_url)
        self.hostname = get_str_clean(default_s, "hostname", self.hostname)
        self.invoice_allow_donations = default_s.getboolean("invoiceAllowDonations", self.invoice_allow_donations)
        self.invoice_default_amount = get_int_safe(default_s, "invoiceDefaultAmount", self.invoice_default_amount)
        self.lcd_rotate = default_s.getboolean("lcdrotate", self.lcd_rotate)
        self.lnd_address = get_str_clean(default_s, "lndAddress", self.lnd_address)
        self.lnd_port = get_str_clean(default_s, "lndPort", self.lnd_port)
        self.network = get_str_clean(default_s, "network", self.network)
        self.public_ip = get_str_clean(default_s, "publicIP", self.public_ip)
        self.rtl_web_interface = default_s.getboolean("rtlWebinterface", self.rtl_web_interface)
        self.run_behind_tor = default_s.getboolean("runBehindTor", self.run_behind_tor)
        self.ssh_tunnel = get_str_clean(default_s, "sshtunnel", self.ssh_tunnel)
        self.touchscreen = default_s.getboolean("touchscreen", self.touchscreen)
        self.version = get_str_clean(default_s, "raspiBlitzVersion", self.version) 
Example #8
Source File: config.py    From raspiblitz with MIT License 5 votes vote down vote up
def reload(self):
        """load config from file"""
        parser = ConfigParser()

        log.debug("loading config from file: {}".format(self.abs_path))
        with open(self.abs_path) as f:
            parser.read_string("[{}]\n".format(DEFAULTSECT) + f.read())

        default_s = parser[DEFAULTSECT]

        self.auto_nat_discovery = default_s.getboolean("autoNatDiscovery", self.auto_nat_discovery)
        self.auto_pilot = default_s.getboolean("autoPilot", self.auto_pilot)
        self.auto_unlock = default_s.getboolean("autoUnlock", self.auto_unlock)
        self.chain = get_str_clean(default_s, "chain", self.chain)
        self.dynDomain = get_str_clean(default_s, "dynDomain", self.dynDomain)
        self.dyn_update_url = get_str_clean(default_s, "dynUpdateUrl", self.dyn_update_url)
        self.hostname = get_str_clean(default_s, "hostname", self.hostname)
        self.invoice_allow_donations = default_s.getboolean("invoiceAllowDonations", self.invoice_allow_donations)
        self.invoice_default_amount = get_int_safe(default_s, "invoiceDefaultAmount", self.invoice_default_amount)
        self.lcd_rotate = default_s.getboolean("lcdrotate", self.lcd_rotate)
        self.lnd_address = get_str_clean(default_s, "lndAddress", self.lnd_address)
        self.lnd_port = get_str_clean(default_s, "lndPort", self.lnd_port)
        self.network = get_str_clean(default_s, "network", self.network)
        self.public_ip = get_str_clean(default_s, "publicIP", self.public_ip)
        self.rtl_web_interface = default_s.getboolean("rtlWebinterface", self.rtl_web_interface)
        self.run_behind_tor = default_s.getboolean("runBehindTor", self.run_behind_tor)
        self.ssh_tunnel = get_str_clean(default_s, "sshtunnel", self.ssh_tunnel)
        self.touchscreen = default_s.getboolean("touchscreen", self.touchscreen)
        self.version = get_str_clean(default_s, "raspiBlitzVersion", self.version) 
Example #9
Source File: test_configparser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def fromstring(self, string, defaults=None):
        cf = self.newconfig(defaults)
        cf.read_string(string)
        cf_copy = self.newconfig()
        cf_copy.read_dict(cf)
        # we have to clean up option duplicates that appeared because of
        # the magic DEFAULTSECT behaviour.
        for section in cf_copy.values():
            if section.name == self.default_section:
                continue
            for default, value in cf[self.default_section].items():
                if section[default] == value:
                    del section[default]
        return cf_copy 
Example #10
Source File: test_config.py    From data.world-py with Apache License 2.0 5 votes vote down vote up
def default_config_file(config_file_path):
    config_parser = configparser.ConfigParser()
    config_parser.set(configparser.DEFAULTSECT, 'auth_token', 'file_token')
    config_parser.write(open(config_file_path, 'w'))


# Tests 
Example #11
Source File: config.py    From data.world-py with Apache License 2.0 5 votes vote down vote up
def __init__(self, profile='default', **kwargs):
        super(FileConfig, self).__init__()

        # Overrides, for testing
        self._config_file_path = path.expanduser(
            kwargs.get('config_file_path', '~/.dw/config'))
        legacy_file_path = path.expanduser(
            kwargs.get('legacy_file_path', '~/.data.world'))

        if not path.isdir(path.dirname(self._config_file_path)):
            os.makedirs(path.dirname(self._config_file_path))

        self._config_parser = (configparser.ConfigParser()
                               if six.PY3 else configparser.SafeConfigParser())

        if path.isfile(self._config_file_path):
            self._config_parser.read_file(open(self._config_file_path))
            if self.__migrate_invalid_defaults(self._config_parser) > 0:
                self.save()
        elif path.isfile(legacy_file_path):
            self._config_parser = self.__migrate_config(legacy_file_path)
            self.save()

        self._profile = profile
        self._section = (profile
                         if profile.lower() != configparser.DEFAULTSECT.lower()
                         else configparser.DEFAULTSECT)

        if not path.isdir(path.dirname(self.cache_dir)):
            os.makedirs(path.dirname(self.cache_dir)) 
Example #12
Source File: config.py    From data.world-py with Apache License 2.0 5 votes vote down vote up
def auth_token(self, auth_token):
        """

        :param auth_token:

        """
        if (self._section != configparser.DEFAULTSECT and
                not self._config_parser.has_section(self._section)):
            self._config_parser.add_section(self._section)
        self._config_parser.set(self._section, 'auth_token', auth_token) 
Example #13
Source File: test_configparser.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def fromstring(self, string, defaults=None):
        cf = self.newconfig(defaults)
        cf.read_string(string)
        cf_copy = self.newconfig()
        cf_copy.read_dict(cf)
        # we have to clean up option duplicates that appeared because of
        # the magic DEFAULTSECT behaviour.
        for section in cf_copy.values():
            if section.name == self.default_section:
                continue
            for default, value in cf[self.default_section].items():
                if section[default] == value:
                    del section[default]
        return cf_copy 
Example #14
Source File: bindings.py    From citest with Apache License 2.0 5 votes vote down vote up
def _do_get(self, name, default_value):
    """Helper function for looking up binding values.

    Args:
      name: [string] The name of the binding will be normalized internally.
      default_value: [string] The value to return if not otherwise found.

    Returns:
      The binding value as either an override, config_value or default value.
      Config values will come from the first section it is found in (or the
      specific section this instance was configured for).
    """
    key = _normalize_key(name)
    if key in self.__overrides:
      return _normalize_value(self.__overrides[key])

    all_sections = ([self.__section]
                    if self.__section
                    else self.__config_parser.sections())
    if not all_sections:
      all_sections = [ConfigParser.DEFAULTSECT]

    for section in all_sections:
      if self.__config_parser.has_option(section, key):
        return _normalize_value(self.__config_parser.get(section, key)
                                or default_value)

    lazy_init = self.__lazy_initializers.get(key)
    if lazy_init is not None:
      lazy_value = lazy_init(self, key)
      if lazy_value is not None:
        self.__overrides[key] = lazy_value
        return _normalize_value(lazy_value)

    if key in self.__config_parser.defaults():
      return _normalize_value(self.__config_parser.defaults()[key])

    return _normalize_value(self.__defaults.get(key, default_value)) 
Example #15
Source File: test_configparser.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def fromstring(self, string, defaults=None):
        cf = self.newconfig(defaults)
        cf.read_string(string)
        cf_copy = self.newconfig()
        cf_copy.read_dict(cf)
        # we have to clean up option duplicates that appeared because of
        # the magic DEFAULTSECT behaviour.
        for section in cf_copy.values():
            if section.name == self.default_section:
                continue
            for default, value in cf[self.default_section].items():
                if section[default] == value:
                    del section[default]
        return cf_copy 
Example #16
Source File: config.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def _write(self, fp):
        """Write an .ini-format representation of the configuration state in
        git compatible format"""
        def write_section(name, section_dict):
            fp.write(("[%s]\n" % name).encode(defenc))
            for (key, value) in section_dict.items():
                if key != "__name__":
                    fp.write(("\t%s = %s\n" % (key, self._value_to_string(value).replace('\n', '\n\t'))).encode(defenc))
                # END if key is not __name__
        # END section writing

        if self._defaults:
            write_section(cp.DEFAULTSECT, self._defaults)
        for name, value in self._sections.items():
            write_section(name, value)