Python six.moves.configparser.NoOptionError() Examples

The following are 28 code examples of six.moves.configparser.NoOptionError(). 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 six.moves.configparser , or try the search function .
Example #1
Source File: parser.py    From pipenv with MIT License 6 votes vote down vote up
def parse(self):
        """

        :return:
        """
        parser = SafeConfigParser()
        parser.readfp(StringIO(self.obj.content))
        for section in parser.sections():
            try:
                content = parser.get(section=section, option="deps")
                for n, line in enumerate(content.splitlines()):
                    if self.is_marked_line(line):
                        continue
                    if line:
                        req = RequirementsTXTLineParser.parse(line)
                        if req:
                            req.dependency_type = self.obj.file_type
                            self.obj.dependencies.append(req)
            except NoOptionError:
                pass 
Example #2
Source File: __main__.py    From profiling with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def config_default(option, default=None, type=None, section=cli.name):
    """Guesses a default value of a CLI option from the configuration.

    ::

       @click.option('--locale', default=config_default('locale'))

    """
    def f(option=option, default=default, type=type, section=section):
        config = read_config()
        if type is None and default is not None:
            # detect type from default.
            type = builtins.type(default)
        get_option = option_getter(type)
        try:
            return get_option(config, section, option)
        except (NoOptionError, NoSectionError):
            return default
    return f 
Example #3
Source File: __main__.py    From profiling with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def config_flag(option, value, default=False, section=cli.name):
    """Guesses whether a CLI flag should be turned on or off from the
    configuration.  If the configuration option value is same with the given
    value, it returns ``True``.

    ::

       @click.option('--ko-kr', 'locale', is_flag=True,
                     default=config_flag('locale', 'ko_KR'))

    """
    class x(object):
        def __bool__(self, option=option, value=value,
                     default=default, section=section):
            config = read_config()
            type = builtins.type(value)
            get_option = option_getter(type)
            try:
                return get_option(config, section, option) == value
            except (NoOptionError, NoSectionError):
                return default
        __nonzero__ = __bool__
    return x() 
Example #4
Source File: core.py    From pycbc with GNU General Public License v3.0 6 votes vote down vote up
def get_opt(self, opt):
        """Get value of option from configuration file

        Parameters
        -----------
        opt : string
            Name of option (e.g. output-file-format)

        Returns
        --------
        value : string
            The value for the option. Returns None if option not present.
        """
        for sec in self.sections:
            try:
                key = self.cp.get(sec, opt)
                if key:
                    return key
            except ConfigParser.NoOptionError:
                pass

        return None 
Example #5
Source File: sydent.py    From sydent with Apache License 2.0 6 votes vote down vote up
def run(self):
        self.clientApiHttpServer.setup()
        self.replicationHttpsServer.setup()
        self.pusher.setup()

        internalport = self.cfg.get('http', 'internalapi.http.port')
        if internalport:
            try:
                interface = self.cfg.get('http', 'internalapi.http.bind_address')
            except configparser.NoOptionError:
                interface = '::1'
            self.internalApiHttpServer = InternalApiHttpServer(self)
            self.internalApiHttpServer.setup(interface, int(internalport))

        if self.pidfile:
            with open(self.pidfile, 'w') as pidfile:
                pidfile.write(str(os.getpid()) + "\n")

        self.reactor.run() 
Example #6
Source File: cli.py    From mygeotab-python with Apache License 2.0 6 votes vote down vote up
def load(self, name=None):
        config = configparser.ConfigParser()
        config.read(self._get_config_file())
        try:
            if name is None:
                sections = config.sections()
                if len(sections) < 1:
                    self.credentials = None
                    return
                section_name = sections[-1]
            else:
                section_name = self._section_name(name)
            username = config.get(section_name, "username")
            session_id = config.get(section_name, "session_id")
            database = config.get(section_name, "database")
            server = config.get(section_name, "server")
            self.credentials = mygeotab.Credentials(username, session_id, database, server)
        except configparser.NoSectionError:
            self.credentials = None
        except configparser.NoOptionError:
            self.credentials = None 
Example #7
Source File: config.py    From heat-translator with Apache License 2.0 5 votes vote down vote up
def get_value(cls, section, key):
        try:
            value = cls._translator_config.get(section, key)
        except configparser.NoOptionError:
            raise exception.ConfOptionNotDefined(key=key, section=section)
        except configparser.NoSectionError:
            raise exception.ConfSectionNotDefined(section=section)

        return value 
Example #8
Source File: configparser.py    From platoon with MIT License 5 votes vote down vote up
def fetch_hosts():
    """A successful search returns a list of host to participate in a multi-node
    platoon. An unsuccessful search raises a KeyError.

    The (decreasing) priority order is:
    - PLATOON_HOSTS
    - PLATOONRC files (if they exist) from right to left
    - working directory's ./.platoonrc
    - ~/.platoonrc

    """
    # first try to have PLATOON_HOSTS
    if PLATOON_HOSTS:
        splitter = shlex.shlex(PLATOON_HOSTS, posix=True)
        splitter.whitespace += ','
        splitter.whitespace_split = True
        return list(splitter)

    # next try to find it in the config file
    try:
        try:
            hosts = platoon_cfg.get("platoon", "hosts")
        except ConfigParser.InterpolationError:
            hosts = platoon_raw_cfg.get("platoon", "hosts")
    except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
        raise KeyError("hosts")
    splitter = shlex.shlex(hosts, posix=True)
    splitter.whitespace += ','
    splitter.whitespace_split = True
    return list(splitter) 
Example #9
Source File: configparser.py    From platoon with MIT License 5 votes vote down vote up
def fetch_devices_for_host(host):
    """A successful search returns a list of theano devices' string values.
    An unsuccessful search raises a KeyError.

    The (decreasing) priority order is:
    - PLATOON_DEVICES
    - PLATOONRC files (if they exist) from right to left
    - working directory's ./.platoonrc
    - ~/.platoonrc

    """
    # first try to have PLATOON_DEVICES
    if PLATOON_DEVICES:
        splitter = shlex.shlex(PLATOON_DEVICES, posix=True)
        splitter.whitespace += ','
        splitter.whitespace_split = True
        return list(splitter)

    # next try to find it in the config file
    try:
        try:
            devices = platoon_cfg.get("devices", host)
        except ConfigParser.InterpolationError:
            devices = platoon_raw_cfg.get("devices", host)
    except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
        raise KeyError(host)
    splitter = shlex.shlex(devices, posix=True)
    splitter.whitespace += ','
    splitter.whitespace_split = True
    return list(splitter) 
Example #10
Source File: config.py    From geonotebook with Apache License 2.0 5 votes vote down vote up
def log_level(self):
        try:
            return getattr(logging, self.config.get("default", "log_level"))
        except (AttributeError, configparser.NoOptionError):
            return logging.WARNING 
Example #11
Source File: app.py    From autologin with Apache License 2.0 5 votes vote down vote up
def init_app():
    # Read config (defaults are in autologin.conf)
    config = configparser.ConfigParser()
    # Read default config
    default_config = os.path.join(server_path, 'autologin.cfg')
    config.read(default_config)
    # Override by user-supplied config
    custom_configs = config.read([
        os.path.expanduser('~/.autologin.cfg'),
        '/etc/autologin.cfg',
        ])

    # Initiate flask app
    app = Flask(__name__)
    app.secret_key = config.get('autologin', 'secret_key')
    try:
        db_path = config.get('autologin', 'db')
    except configparser.NoOptionError:
        db_path = os.path.join(os.path.dirname(__file__), 'db.sqlite')
    else:
        if not os.path.isabs(db_path) and custom_configs:
            where = custom_configs[0] if len(custom_configs) == 1 else \
                    'one of {}'.format(', '.join(custom_configs))
            raise RuntimeError(
                'You must specify an absolute path to the database. '
                'Invalid relative path "{db_path}" in {where}'
                .format(db_path=db_path, where=where))
    assert os.path.isabs(db_path), 'Absolute path expected'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(db_path)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    return app 
Example #12
Source File: test_config.py    From imap-cli with MIT License 5 votes vote down vote up
def test_sasl_auth_no_initial_response(self):
        self.config_file.write('sasl_auth = XOAUTH2\n')
        self.config_file.seek(SEEK_SET, 0)

        self.assertRaises(configparser.NoOptionError,
                          config.new_context_from_file,
                          self.config_file.name,
                          section='imap') 
Example #13
Source File: diskbenchmark.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def read(benchmark_result_file):
    """
    Read benchmark
    :param benchmark_result_file: benchmark result file
    :return: {device: {metric: value, }, }
    """
    result = {}
    config = configparser.SafeConfigParser()
    with io.open(benchmark_result_file) as fp:
        config.readfp(fp)  # pylint: disable=deprecated-method
    for section in config.sections():
        try:
            device = config.get(section, _DEVICE)
            result[device] = {}
            for metric in Metrics:
                result[device][metric.value] = config.get(
                    section,
                    metric.value
                )
        except configparser.NoOptionError:
            _LOGGER.error(
                'Incorrect section in %s',
                benchmark_result_file
            )

    return result 
Example #14
Source File: ldap-setup.py    From allura with Apache License 2.0 5 votes vote down vote up
def get_value(key, default):
    try:
        default = config.get('scm', key)
    except NoOptionError:
        pass
    value = input('%s? [%s]' % (key, default))
    if not value:
        value = default
    config.set('scm', key, value)
    with open('.setup-scm-cache', 'w') as fp:
        config.write(fp)
    return value 
Example #15
Source File: pytest_pyramid_server.py    From pytest-plugins with MIT License 5 votes vote down vote up
def pre_setup(self):
        """ Make a copy of at the ini files and set the port number and host in the new testing.ini
        """
        self.working_config = self.workspace / self.config_filename

        # We need the other ini files as well here as they may be chained
        for filename in glob.glob(os.path.join(self.config_dir, '*.ini')):
            shutil.copy(filename, self.workspace)

        Path.copy(self.original_config, self.working_config)

        parser = configparser.ConfigParser()
        parser.read(self.original_config)
        parser.set('server:main', 'port', str(self.port))
        parser.set('server:main', 'host', self.hostname)
        [parser.set(section, k, v) for section, cfg in self.extra_config_vars.items() for (k, v) in cfg.items()]
        with open(str(self.working_config), 'w') as fp:
            parser.write(fp)

        try:
            parser.get('app:main', 'url_prefix')
        except configparser.NoOptionError:
            parser.set('app:main', 'url_prefix', '')

        # Set the uri to be the external hostname and the url prefix
        self._uri = "http://%s:%s/%s" % (os.uname()[1], self.port, parser.get('app:main', 'url_prefix')) 
Example #16
Source File: config.py    From heat-translator with Apache License 2.0 5 votes vote down vote up
def get_all_values(cls):
        values = []
        for section in cls._sections:
            try:
                values.extend(cls._translator_config.items(section=section))
            except configparser.NoOptionError:
                raise exception.ConfSectionNotDefined(section=section)

        return values 
Example #17
Source File: privacyidea_apache.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_config():
    """
    Try to read config from the file /etc/privacyidea/apache.conf

    The config values are
        redis = IPAddress:Port
        privacyidea = https://hostname/path
        sslverify = True | filename to CA bundle
        timeout = seconds
    :return: The configuration
    :rtype: dict
    """
    config_file = configparser.ConfigParser()
    config_file.read(CONFIG_FILE)
    PRIVACYIDEA = DEFAULT_PRIVACYIDEA
    SSLVERIFY = DEFAULT_SSLVERIFY
    REDIS = DEFAULT_REDIS
    TIMEOUT = DEFAULT_TIMEOUT
    try:
        PRIVACYIDEA = config_file.get("DEFAULT", "privacyidea") or DEFAULT_PRIVACYIDEA
        SSLVERIFY = config_file.get("DEFAULT", "sslverify") or DEFAULT_SSLVERIFY
        if SSLVERIFY == "False":
            SSLVERIFY = False
        elif SSLVERIFY == "True":
            SSLVERIFY = True
        REDIS = config_file.get("DEFAULT", "redis") or DEFAULT_REDIS
        TIMEOUT = config_file.get("DEFAULT", "timeout") or DEFAULT_TIMEOUT
        TIMEOUT = int(TIMEOUT)
    except configparser.NoOptionError as exx:
        syslog.syslog(syslog.LOG_ERR, "{0!s}".format(exx))
    syslog.syslog(syslog.LOG_DEBUG, "Reading configuration {0!s}, {1!s}, {2!s}".format(
        PRIVACYIDEA, REDIS, SSLVERIFY))
    return PRIVACYIDEA, REDIS, SSLVERIFY, TIMEOUT 
Example #18
Source File: config_test.py    From girder_worker with Apache License 2.0 5 votes vote down vote up
def testConfigCommands(self):
        self.assertFalse(os.path.exists(local_cfg))

        info = self._runConfigScript(['--help'])
        self.assertEqual(info['rc'], 0)
        self.assertEqual(info['stderr'], '')
        self.assertIn('Get and set configuration values for the worker',
                      info['stdout'])

        info = self._runConfigScript(['list'])
        self.assertEqual(info['rc'], 0)
        self.assertIn('[girder_worker]', info['stdout'])

        info = self._runConfigScript(['get', 'celery', 'app_main'])
        self.assertEqual(info['rc'], 0)
        self.assertEqual(info['stdout'].strip(), 'girder_worker')

        info = self._runConfigScript(['set', 'celery', 'app_main', 'foo'])
        self.assertEqual(info['rc'], 0)

        info = self._runConfigScript(['get', 'celery', 'app_main'])
        self.assertEqual(info['rc'], 0)
        self.assertEqual(info['stdout'].strip(), 'foo')

        info = self._runConfigScript(['rm', 'celery', 'app_main'])
        self.assertEqual(info['rc'], 0)

        with self.assertRaises(NoOptionError):
            self._runConfigScript(['get', 'celery', 'app_main']) 
Example #19
Source File: credential_store.py    From azure-devops-cli-extension with MIT License 5 votes vote down vote up
def get_PAT_from_file(self, key):
        ensure_dir(AZ_DEVOPS_GLOBAL_CONFIG_DIR)
        logger.debug('Keyring not configured properly or package not found.'
                     'Looking for credentials with key:%s in the file: %s', key, self._PAT_FILE)
        creds_list = self._get_credentials_list()
        try:
            return creds_list.get(key, self._USERNAME)
        except (configparser.NoOptionError, configparser.NoSectionError):
            return None 
Example #20
Source File: aws.py    From commcare-cloud with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _has_valid_v1_session_credentials(aws_profile):
    config = configparser.ConfigParser()
    config.read(os.path.realpath(AWS_CREDENTIALS_PATH))
    if aws_profile not in config.sections():
        return False
    try:
        expiration = datetime.strptime(config.get(aws_profile, 'expiration'), "%Y-%m-%dT%H:%M:%SZ")
    except configparser.NoOptionError:
        return False

    return datetime.utcnow() < expiration 
Example #21
Source File: aws.py    From commcare-cloud with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _has_profile_for_sso(aws_profile):
    config = configparser.ConfigParser()
    config.read(os.path.realpath(AWS_CONFIG_PATH))
    section = 'profile {}'.format(aws_profile)

    if section not in config.sections():
        return False

    try:
        config.get(section, 'sso_start_url')
    except configparser.NoOptionError:
        return False

    return True 
Example #22
Source File: test_deployment.py    From Dallinger with MIT License 5 votes vote down vote up
def test_setup_excludes_sensitive_config(self, setup_experiment):
        config = get_config()
        # Auto detected as sensitive
        config.register("a_password", six.text_type)
        # Manually registered as sensitive
        config.register("something_sensitive", six.text_type, sensitive=True)
        # Not sensitive at all
        config.register("something_normal", six.text_type)

        config.extend(
            {
                "a_password": "secret thing",
                "something_sensitive": "hide this",
                "something_normal": "show this",
            }
        )

        exp_id, dst = setup_experiment(log=mock.Mock())

        # The temp dir should have a config with the sensitive variables missing
        deploy_config = configparser.ConfigParser()
        deploy_config.read(os.path.join(dst, "config.txt"))
        assert deploy_config.get("Parameters", "something_normal") == "show this"
        with raises(configparser.NoOptionError):
            deploy_config.get("Parameters", "a_password")
        with raises(configparser.NoOptionError):
            deploy_config.get("Parameters", "something_sensitive") 
Example #23
Source File: config.py    From virt-who with GNU General Public License v2.0 4 votes vote down vote up
def parse_file(filename):
    # Parse a file into a dict of name: options_dict
    # options_dict is a dict of option_name: value

    # First try to find duplicates, which are not critical, but
    # it breaks parsing the config file
    if six.PY3:
        parser = StripQuotesConfigParser(strict=True)
        try:
            parser.read(filename)
        except DuplicateOptionError as err:
            logger.warning(str(err))
        except Exception as err:
            pass
        parser = StripQuotesConfigParser(strict=False)
    else:
        parser = StripQuotesConfigParser()

    sections = {}

    try:
        fname = parser.read(filename)
        if len(fname) == 0:
            logger.error("Unable to read configuration file %s", filename)
        else:
            sections = _all_parser_sections(parser)
    except MissingSectionHeaderError:
        logger.error("Configuration file %s contains no section headers", filename)
    except NoOptionError as e:
        logger.error(str(e))
    except InvalidPasswordFormat as e:
        logger.error(str(e))
    except InvalidOption as e:
        # When a configuration section has an Invalid Option, continue
        # See https://bugzilla.redhat.com/show_bug.cgi?id=1457101 for more info
        logger.warn("Invalid configuration detected: %s", str(e))
    except DuplicateOptionError as e:
        logger.warning(str(e))
    except Exception as e:
        logger.error('Config file "%s" skipped because of an error: %s',
                     filename, str(e))
    return sections


# Helper methods used to validate parameters given to virt-who 
Example #24
Source File: main.py    From doc8 with Apache License 2.0 4 votes vote down vote up
def extract_config(args):
    parser = configparser.RawConfigParser()
    read_files = []
    if args["config"]:
        for fn in args["config"]:
            with open(fn, "r") as fh:
                parser.readfp(fh, filename=fn)
                read_files.append(fn)
    else:
        read_files.extend(parser.read(CONFIG_FILENAMES))
    if not read_files:
        return {}
    cfg = {}
    try:
        cfg["max_line_length"] = parser.getint("doc8", "max-line-length")
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["ignore"] = split_set_type(parser.get("doc8", "ignore"))
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["ignore_path"] = split_set_type(parser.get("doc8", "ignore-path"))
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        ignore_path_errors = parser.get("doc8", "ignore-path-errors")
        ignore_path_errors = split_set_type(ignore_path_errors)
        ignore_path_errors = parse_ignore_path_errors(ignore_path_errors)
        cfg["ignore_path_errors"] = ignore_path_errors
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["allow_long_titles"] = parser.getboolean("doc8", "allow-long-titles")
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["sphinx"] = parser.getboolean("doc8", "sphinx")
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["verbose"] = parser.getboolean("doc8", "verbose")
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["file_encoding"] = parser.get("doc8", "file-encoding")
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        cfg["default_extension"] = parser.get("doc8", "default-extension")
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    try:
        extensions = parser.get("doc8", "extensions")
        extensions = extensions.split(",")
        extensions = [s.strip() for s in extensions if s.strip()]
        if extensions:
            cfg["extension"] = extensions
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    return cfg 
Example #25
Source File: wiki-copy.py    From allura with Apache License 2.0 4 votes vote down vote up
def make_oauth_client(base_url):
    """
    Build an oauth.Client with which callers can query Allura.
    """
    config_file = os.path.join(os.environ['HOME'], '.allurarc')
    cp = ConfigParser()
    cp.read(config_file)

    REQUEST_TOKEN_URL = base_url + '/rest/oauth/request_token'
    AUTHORIZE_URL = base_url + '/rest/oauth/authorize'
    ACCESS_TOKEN_URL = base_url + '/rest/oauth/access_token'
    oauth_key = option(cp, base_url, 'oauth_key',
                       'Forge API OAuth Key (%s/auth/oauth/): ' % base_url)
    oauth_secret = option(cp, base_url, 'oauth_secret',
                          'Forge API Oauth Secret: ')
    consumer = oauth.Consumer(oauth_key, oauth_secret)

    try:
        oauth_token = cp.get(base_url, 'oauth_token')
        oauth_token_secret = cp.get(base_url, 'oauth_token_secret')
    except NoOptionError:
        client = oauth.Client(consumer)
        resp, content = client.request(REQUEST_TOKEN_URL, 'GET')
        assert resp['status'] == '200', resp

        request_token = dict(six.moves.urllib.parse.parse_qsl(content))
        pin_url = "%s?oauth_token=%s" % (
            AUTHORIZE_URL, request_token['oauth_token'])
        if getattr(webbrowser.get(), 'name', '') == 'links':
            # sandboxes
            print(("Go to %s" % pin_url))
        else:
            webbrowser.open(pin_url)
        oauth_verifier = input('What is the PIN? ')

        token = oauth.Token(
            request_token['oauth_token'], request_token['oauth_token_secret'])
        token.set_verifier(oauth_verifier)
        client = oauth.Client(consumer, token)
        resp, content = client.request(ACCESS_TOKEN_URL, "GET")
        access_token = dict(six.moves.urllib.parse.parse_qsl(content))
        oauth_token = access_token['oauth_token']
        oauth_token_secret = access_token['oauth_token_secret']

        cp.set(base_url, 'oauth_token', oauth_token)
        cp.set(base_url, 'oauth_token_secret', oauth_token_secret)

    # save oauth token for later use
    cp.write(open(config_file, 'w'))
    print('Saving oauth tokens in {} for later re-use'.format(config_file))
    print()

    access_token = oauth.Token(oauth_token, oauth_token_secret)
    oauth_client = oauth.Client(consumer, access_token)
    return oauth_client 
Example #26
Source File: peer.py    From sydent with Apache License 2.0 4 votes vote down vote up
def __init__(self, sydent, server_name, port, pubkeys, lastSentVersion):
        """
        :param sydent: The current Sydent instance.
        :type sydent: sydent.sydent.Sydent
        :param server_name: The peer's server name.
        :type server_name: unicode
        :param port: The peer's port.
        :type port: int
        :param pubkeys: The peer's public keys in a dict[key_id, key_b64]
        :type pubkeys: dict[unicode, unicode]
        :param lastSentVersion: The ID of the last association sent to the peer.
        :type lastSentVersion: int
        """
        super(RemotePeer, self).__init__(server_name, pubkeys)
        self.sydent = sydent
        self.port = port
        self.lastSentVersion = lastSentVersion

        # look up or build the replication URL
        try:
            replication_url = sydent.cfg.get(
                "peer.%s" % server_name, "base_replication_url",
            )
        except (configparser.NoSectionError, configparser.NoOptionError):
            if not port:
                port = 1001
            replication_url = "https://%s:%i" % (server_name, port)

        if replication_url[-1:] != '/':
            replication_url += "/"

        replication_url += "_matrix/identity/replicate/v1/push"
        self.replication_url = replication_url

        # Get verify key for this peer

        # Check if their key is base64 or hex encoded
        pubkey = self.pubkeys[SIGNING_KEY_ALGORITHM]
        try:
            # Check for hex encoding
            int(pubkey, 16)

            # Decode hex into bytes
            pubkey_decoded = binascii.unhexlify(pubkey)

            logger.warn("Peer public key of %s is hex encoded. Please update to base64 encoding", server_name)
        except ValueError:
            # Check for base64 encoding
            try:
                pubkey_decoded = decode_base64(pubkey)
            except Exception as e:
                raise ConfigError(
                    "Unable to decode public key for peer %s: %s" % (server_name, e),
                )

        self.verify_key = signedjson.key.decode_verify_key_bytes(SIGNING_KEY_ALGORITHM + ":", pubkey_decoded)

        # Attach metadata
        self.verify_key.alg = SIGNING_KEY_ALGORITHM
        self.verify_key.version = 0 
Example #27
Source File: configuration.py    From pycbc with GNU General Public License v3.0 4 votes vote down vote up
def interpolate_string(self, testString, section):
        """
        Take a string and replace all example of ExtendedInterpolation
        formatting within the string with the exact value.

        For values like ${example} this is replaced with the value that
        corresponds to the option called example ***in the same section***

        For values like ${common|example} this is replaced with the value that
        corresponds to the option example in the section [common]. Note that
        in the python3 config parser this is ${common:example} but python2.7
        interprets the : the same as a = and this breaks things

        Nested interpolation is not supported here.

        Parameters
        ----------
        testString : String
            The string to parse and interpolate
        section : String
            The current section of the ConfigParser object

        Returns
        ----------
        testString : String
            Interpolated string
        """

        # First check if any interpolation is needed and abort if not
        reObj = re.search(r"\$\{.*?\}", testString)
        while reObj:
            # Not really sure how this works, but this will obtain the first
            # instance of a string contained within ${....}
            repString = (reObj).group(0)[2:-1]
            # Need to test which of the two formats we have
            splitString = repString.split('|')
            if len(splitString) == 1:
                try:
                    testString = testString.replace('${'+repString+'}',\
                                            self.get(section,splitString[0]))
                except ConfigParser.NoOptionError:
                    print("Substitution failed")
                    raise
            if len(splitString) == 2:
                try:
                    testString = testString.replace('${'+repString+'}',\
                                       self.get(splitString[0],splitString[1]))
                except ConfigParser.NoOptionError:
                    print("Substitution failed")
                    raise
            reObj = re.search(r"\$\{.*?\}", testString)

        return testString 
Example #28
Source File: utils.py    From glance_store with Apache License 2.0 4 votes vote down vote up
def _load_config(self):
        if self.backend_group:
            scf = getattr(self.conf,
                          self.backend_group).swift_store_config_file
        else:
            scf = self.conf.glance_store.swift_store_config_file
        try:
            conf_file = self.conf.find_file(scf)
            CONFIG.read(conf_file)
        except Exception as e:
            msg = (_("swift config file "
                     "%(conf)s:%(exc)s not found"),
                   {'conf': scf,
                    'exc': e})
            LOG.error(msg)
            raise exceptions.BadStoreConfiguration(store_name='swift',
                                                   reason=msg)
        account_params = {}
        account_references = CONFIG.sections()

        for ref in account_references:
            reference = {}
            try:
                for param in ('auth_address',
                              'user',
                              'key',
                              'project_domain_id',
                              'project_domain_name',
                              'user_domain_id',
                              'user_domain_name'):
                    reference[param] = CONFIG.get(ref, param)

                try:
                    reference['auth_version'] = CONFIG.get(ref, 'auth_version')
                except configparser.NoOptionError:
                    if self.backend_group:
                        av = getattr(
                            self.conf,
                            self.backend_group).swift_store_auth_version
                    else:
                        av = self.conf.glance_store.swift_store_auth_version
                    reference['auth_version'] = av

                account_params[ref] = reference
            except (ValueError, SyntaxError, configparser.NoOptionError):
                LOG.exception(_LE("Invalid format of swift store config cfg"))
        return account_params