当前位置: 首页>>代码示例>>Python>>正文


Python strutils.bool_from_string方法代码示例

本文整理汇总了Python中oslo_utils.strutils.bool_from_string方法的典型用法代码示例。如果您正苦于以下问题:Python strutils.bool_from_string方法的具体用法?Python strutils.bool_from_string怎么用?Python strutils.bool_from_string使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在oslo_utils.strutils的用法示例。


在下文中一共展示了strutils.bool_from_string方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _update_forced_down

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def _update_forced_down(self, context, body):
        """Set or unset forced_down flag for the service"""
        try:
            forced_down = strutils.bool_from_string(body['forced_down'], True)
        except ValueError:
            bools = ', '.join(strutils.TRUE_STRINGS + strutils.FALSE_STRINGS)
            raise exception.InvalidValue(_('Valid forced_down values are: %s')
                                         % bools)
        self._update(context, body['host'], body['binary'],
                     {"forced_down": forced_down})
        res = {
            'service': {
                'host': body['host'],
                'binary': body['binary'],
                'forced_down': forced_down
            },
        }
        return res 
开发者ID:openstack,项目名称:zun,代码行数:20,代码来源:zun_services.py

示例2: search

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def search(self, image, image_driver=None, exact_match=False):
        """Search a specific image

        :param image:  Name of the image.
        :param image_driver: Name of the image driver (glance, docker).
        :param exact_match: if True, exact match the image name.
        """
        context = pecan.request.context
        policy.enforce(context, "image:search",
                       action="image:search")
        LOG.debug('Calling compute.image_search with %s', image)
        try:
            exact_match = strutils.bool_from_string(exact_match, strict=True)
        except ValueError:
            bools = ', '.join(strutils.TRUE_STRINGS + strutils.FALSE_STRINGS)
            raise exception.InvalidValue(_('Valid exact_match values are: %s')
                                         % bools)
        # Valiadtion accepts 'None' so need to convert it to None
        image_driver = api_utils.string_or_none(image_driver)
        if not image_driver:
            image_driver = CONF.default_image_driver

        return pecan.request.compute_api.image_search(context, image,
                                                      image_driver,
                                                      exact_match, None) 
开发者ID:openstack,项目名称:zun,代码行数:27,代码来源:images.py

示例3: from_json

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def from_json(json):
        if json.get('next_hop') and json.get('nexthop'):
            msg = ('Invalid Route JSON object with both next_hop and nexthop '
                   'configured. Use either next_hop or nexthop.')
            raise InvalidConfigException(msg)

        if json.get('ip_netmask') and json.get('destination'):
            msg = ('Invalid Route JSON object with both ip_netmask and '
                   'destination configured. Use either ip_netmask or '
                   'destination.')
            raise InvalidConfigException(msg)

        next_hop = json.get('next_hop', json.get('nexthop'))
        if next_hop is None:
            msg = ('Route JSON objects require next_hop or nexthop to be '
                   'configured.')
            raise InvalidConfigException(msg)
        ip_netmask = json.get('ip_netmask', json.get('destination', ""))
        route_options = json.get('route_options', "")
        default = strutils.bool_from_string(str(json.get('default', False)))
        route_options = json.get('route_options', "")
        route_table = json.get('table', "")
        return Route(next_hop, ip_netmask, default, route_options, route_table) 
开发者ID:openstack,项目名称:os-net-config,代码行数:25,代码来源:objects.py

示例4: apply_filter

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def apply_filter(query, model, filters):
        translated_filters = {}
        child_map = {}
        # Convert enabled to proper type
        if 'enabled' in filters:
            filters['enabled'] = strutils.bool_from_string(
                filters['enabled'])
        for attr, name_map in model.__v2_wsme__._child_map.items():
            for k, v in name_map.items():
                if attr in filters and k in filters[attr]:
                    child_map.setdefault(attr, {}).update(
                        {k: filters[attr].pop(k)})
            filters.pop(attr, None)

        for k, v in model.__v2_wsme__._type_to_model_map.items():
            if k in filters:
                translated_filters[v] = filters.pop(k)
        translated_filters.update(filters)
        if translated_filters:
            query = query.filter_by(**translated_filters)
        for k, v in child_map.items():
            query = query.join(getattr(model, k)).filter_by(**v)
        return query 
开发者ID:openstack,项目名称:octavia,代码行数:25,代码来源:base_models.py

示例5: get_password

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def get_password(max_password_prompts=3):
    """Read password from TTY."""
    verify = strutils.bool_from_string(env("OS_VERIFY_PASSWORD"))
    pw = None
    if hasattr(sys.stdin, "isatty") and sys.stdin.isatty():
        # Check for Ctrl-D
        try:
            for __ in moves.range(max_password_prompts):
                pw1 = getpass.getpass("OS Password: ")
                if verify:
                    pw2 = getpass.getpass("Please verify: ")
                else:
                    pw2 = pw1
                if pw1 == pw2 and pw1:
                    pw = pw1
                    break
        except EOFError:
            pass
    return pw 
开发者ID:nttcom,项目名称:eclcli,代码行数:21,代码来源:cliutils.py

示例6: fix_greendns_ipv6

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def fix_greendns_ipv6():
    if dnspython_installed:
        # All of this is because if dnspython is present in your environment
        # then eventlet monkeypatches socket.getaddrinfo() with an
        # implementation which doesn't work for IPv6. What we're checking here
        # is that the magic environment variable was set when the import
        # happened.
        nogreendns = 'EVENTLET_NO_GREENDNS'
        flag = os.environ.get(nogreendns, '')
        if 'eventlet' in sys.modules and not strutils.bool_from_string(flag):
            msg = _("It appears that the eventlet module has been "
                    "imported prior to setting %s='yes'. It is currently "
                    "necessary to disable eventlet.greendns "
                    "if using ipv6 since eventlet.greendns currently "
                    "breaks with ipv6 addresses. Please ensure that "
                    "eventlet is not imported prior to this being set.")
            raise ImportError(msg % (nogreendns))

        os.environ[nogreendns] = 'yes' 
开发者ID:openstack,项目名称:searchlight,代码行数:21,代码来源:__init__.py

示例7: _set_cert_manager_params

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def _set_cert_manager_params(self, context, cluster, extra_params):
        cert_manager_api = cluster.labels.get('cert_manager_api')
        if strutils.bool_from_string(cert_manager_api):
            extra_params['cert_manager_api'] = cert_manager_api
            ca_cert = cert_manager.get_cluster_ca_certificate(cluster,
                                                              context=context)
            if six.PY3 and isinstance(ca_cert.get_private_key_passphrase(),
                                      six.text_type):
                extra_params['ca_key'] = x509.decrypt_key(
                    ca_cert.get_private_key(),
                    ca_cert.get_private_key_passphrase().encode()
                ).decode().replace("\n", "\\n")
            else:
                extra_params['ca_key'] = x509.decrypt_key(
                    ca_cert.get_private_key(),
                    ca_cert.get_private_key_passphrase()).replace("\n", "\\n") 
开发者ID:openstack,项目名称:magnum,代码行数:18,代码来源:k8s_fedora_template_def.py

示例8: set_cluster_peer_policy

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def set_cluster_peer_policy(self, is_unauthenticated_access_permitted=None,
                                passphrase_minimum_length=None):
        """Modifies the cluster peering policy configuration."""

        if not self.features.CLUSTER_PEER_POLICY:
            return

        if (is_unauthenticated_access_permitted is None and
                passphrase_minimum_length is None):
            return

        api_args = {}
        if is_unauthenticated_access_permitted is not None:
            api_args['is-unauthenticated-access-permitted'] = (
                'true' if strutils.bool_from_string(
                    is_unauthenticated_access_permitted) else 'false')
        if passphrase_minimum_length is not None:
            api_args['passphrase-minlength'] = six.text_type(
                passphrase_minimum_length)

        self.send_request('cluster-peer-policy-modify', api_args) 
开发者ID:openstack,项目名称:manila,代码行数:23,代码来源:client_cmode.py

示例9: parse_boolean_extra_spec

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def parse_boolean_extra_spec(extra_spec_key, extra_spec_value):
    """Parse extra spec values of the form '<is> True' or '<is> False'

    This method returns the boolean value of an extra spec value.  If
    the value does not conform to the standard boolean pattern, it raises
    an InvalidExtraSpec exception.
    """
    if not isinstance(extra_spec_value, six.string_types):
        extra_spec_value = six.text_type(extra_spec_value)

    match = re.match(r'^<is>\s*(?P<value>True|False)$',
                     extra_spec_value.strip(),
                     re.IGNORECASE)
    if match:
        extra_spec_value = match.group('value')
    try:
        return strutils.bool_from_string(extra_spec_value, strict=True)
    except ValueError:
        msg = (_('Invalid boolean extra spec %(key)s : %(value)s') %
               {'key': extra_spec_key, 'value': extra_spec_value})
        raise exception.InvalidExtraSpec(reason=msg) 
开发者ID:openstack,项目名称:manila,代码行数:23,代码来源:share_types.py

示例10: _parse_is_public

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def _parse_is_public(is_public):
        """Parse is_public into something usable.

        * True: API should list public share types only
        * False: API should list private share types only
        * None: API should list both public and private share types
        """
        if is_public is None:
            # preserve default value of showing only public types
            return True
        elif six.text_type(is_public).lower() == "all":
            return None
        else:
            try:
                return strutils.bool_from_string(is_public, strict=True)
            except ValueError:
                msg = _('Invalid is_public filter [%s]') % is_public
                raise exc.HTTPBadRequest(explanation=msg) 
开发者ID:openstack,项目名称:manila,代码行数:20,代码来源:share_types.py

示例11: is_all_tenants

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def is_all_tenants(search_opts):
    """Checks to see if the all_tenants flag is in search_opts

    :param dict search_opts: The search options for a request
    :returns: boolean indicating if all_tenants are being requested or not
    """
    all_tenants = search_opts.get('all_tenants')
    if all_tenants:
        try:
            all_tenants = strutils.bool_from_string(all_tenants, True)
        except ValueError as err:
            raise exception.InvalidInput(six.text_type(err))
    else:
        # The empty string is considered enabling all_tenants
        all_tenants = 'all_tenants' in search_opts
    return all_tenants 
开发者ID:openstack,项目名称:manila,代码行数:18,代码来源:utils.py

示例12: get_bool_from_api_params

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def get_bool_from_api_params(key, params, default=False, strict=True):
    """Parse bool value from request params.

    HTTPBadRequest will be directly raised either of the cases below:
    1. invalid bool string was found by key(with strict on).
    2. key not found while default value is invalid(with strict on).
    """
    param = params.get(key, default)
    try:
        param = strutils.bool_from_string(param,
                                          strict=strict,
                                          default=default)
    except ValueError:
        msg = _('Invalid value %(param)s for %(param_string)s. '
                'Expecting a boolean.') % {'param': param,
                                           'param_string': key}
        raise exc.HTTPBadRequest(explanation=msg)
    return param 
开发者ID:openstack,项目名称:manila,代码行数:20,代码来源:utils.py

示例13: get_all

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def get_all(self, **kwargs):
        LOG.info('list all webhooks with args: %s', kwargs)

        all_tenants = kwargs.get(TenantProps.ALL_TENANTS, False)
        all_tenants = bool_from_string(all_tenants)

        if all_tenants:
            enforce('webhook list:all_tenants', pecan.request.headers,
                    pecan.request.enforcer, {})
        else:
            enforce('webhook list', pecan.request.headers,
                    pecan.request.enforcer, {})

        try:
            return self._get_all(all_tenants)
        except Exception:
            LOG.exception('Failed to list webhooks.')
            abort(404, 'Failed to list webhooks.') 
开发者ID:openstack,项目名称:vitrage,代码行数:20,代码来源:webhook.py

示例14: get

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def get(self, all_tenants=False):
        all_tenants = bool_from_string(all_tenants)
        if all_tenants:
            enforce("get alarms count:all_tenants", pecan.request.headers,
                    pecan.request.enforcer, {})
        else:
            enforce("get alarms count", pecan.request.headers,
                    pecan.request.enforcer, {})

        LOG.info('received get alarm counts')

        try:
            alarm_counts_json = pecan.request.client.call(
                pecan.request.context, 'get_alarm_counts',
                all_tenants=all_tenants)

            return json.loads(alarm_counts_json)

        except Exception:
            LOG.exception('failed to get alarm count.')
            abort(404, 'Failed to get alarm count.') 
开发者ID:openstack,项目名称:vitrage,代码行数:23,代码来源:count.py

示例15: __init__

# 需要导入模块: from oslo_utils import strutils [as 别名]
# 或者: from oslo_utils.strutils import bool_from_string [as 别名]
def __init__(self, flow, flow_detail, backend, options):
        super(ActionEngine, self).__init__(flow, flow_detail, backend, options)
        self._runtime = None
        self._compiled = False
        self._compilation = None
        self._compiler = compiler.PatternCompiler(flow)
        self._lock = threading.RLock()
        self._storage_ensured = False
        self._validated = False
        # Retries are not *currently* executed out of the engines process
        # or thread (this could change in the future if we desire it to).
        self._retry_executor = executor.SerialRetryExecutor()
        self._inject_transient = strutils.bool_from_string(
            self._options.get('inject_transient', True))
        self._gather_statistics = strutils.bool_from_string(
            self._options.get('gather_statistics', True))
        self._statistics = {} 
开发者ID:openstack,项目名称:taskflow,代码行数:19,代码来源:engine.py


注:本文中的oslo_utils.strutils.bool_from_string方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。