예제 #1
0
def bool_from_string(subject, strict=False, default=False):
    """Interpret a string as a boolean.

    A case-insensitive match is performed such that strings matching 't',
    'true', 'on', 'y', 'yes', or '1' are considered True and, when
    `strict=False`, anything else returns the value specified by 'default'.

    Useful for JSON-decoded stuff and config file parsing.

    If `strict=True`, unrecognized values, including None, will raise a
    ValueError which is useful when parsing values passed in from an API call.
    Strings yielding False are 'f', 'false', 'off', 'n', 'no', or '0'.
    """
    if not isinstance(subject, six.string_types):
        subject = six.text_type(subject)

    lowered = subject.strip().lower()

    if lowered in TRUE_STRINGS:
        return True
    elif lowered in FALSE_STRINGS:
        return False
    elif strict:
        acceptable = ', '.join("'%s'" % s
                               for s in sorted(TRUE_STRINGS + FALSE_STRINGS))
        msg = _("Unrecognized value '%(val)s', acceptable values are:"
                " %(acceptable)s") % {
                    'val': subject,
                    'acceptable': acceptable
                }
        raise ValueError(msg)
    else:
        return default
예제 #2
0
def bool_from_string(subject, strict=False, default=False):
    """Interpret a string as a boolean.

    A case-insensitive match is performed such that strings matching 't',
    'true', 'on', 'y', 'yes', or '1' are considered True and, when
    `strict=False`, anything else returns the value specified by 'default'.

    Useful for JSON-decoded stuff and config file parsing.

    If `strict=True`, unrecognized values, including None, will raise a
    ValueError which is useful when parsing values passed in from an API call.
    Strings yielding False are 'f', 'false', 'off', 'n', 'no', or '0'.
    """
    if not isinstance(subject, six.string_types):
        subject = six.text_type(subject)

    lowered = subject.strip().lower()

    if lowered in TRUE_STRINGS:
        return True
    elif lowered in FALSE_STRINGS:
        return False
    elif strict:
        acceptable = ', '.join(
            "'%s'" % s for s in sorted(TRUE_STRINGS + FALSE_STRINGS))
        msg = _("Unrecognized value '%(val)s', acceptable values are:"
                " %(acceptable)s") % {'val': subject,
                                      'acceptable': acceptable}
        raise ValueError(msg)
    else:
        return default
예제 #3
0
def string_to_bytes(text, unit_system='IEC', return_int=False):
    """Converts a string into an float representation of bytes.

    The units supported for IEC ::

        Kb(it), Kib(it), Mb(it), Mib(it), Gb(it), Gib(it), Tb(it), Tib(it)
        KB, KiB, MB, MiB, GB, GiB, TB, TiB

    The units supported for SI ::

        kb(it), Mb(it), Gb(it), Tb(it)
        kB, MB, GB, TB

    Note that the SI unit system does not support capital letter 'K'

    :param text: String input for bytes size conversion.
    :param unit_system: Unit system for byte size conversion.
    :param return_int: If True, returns integer representation of text
                       in bytes. (default: decimal)
    :returns: Numerical representation of text in bytes.
    :raises ValueError: If text has an invalid value.

    """
    try:
        base, reg_ex = UNIT_SYSTEM_INFO[unit_system]
    except KeyError:
        msg = _('Invalid unit system: "%s"') % unit_system
        raise ValueError(msg)
    match = reg_ex.match(text)
    if match:
        magnitude = float(match.group(1))
        unit_prefix = match.group(2)
        if match.group(3) in ['b', 'bit']:
            magnitude /= 8
    else:
        msg = _('Invalid string format: %s') % text
        raise ValueError(msg)
    if not unit_prefix:
        res = magnitude
    else:
        res = magnitude * pow(base, UNIT_PREFIX_EXPONENT[unit_prefix])
    if return_int:
        return int(math.ceil(res))
    return res
예제 #4
0
def string_to_bytes(text, unit_system='IEC', return_int=False):
    """Converts a string into an float representation of bytes.

    The units supported for IEC ::

        Kb(it), Kib(it), Mb(it), Mib(it), Gb(it), Gib(it), Tb(it), Tib(it)
        KB, KiB, MB, MiB, GB, GiB, TB, TiB

    The units supported for SI ::

        kb(it), Mb(it), Gb(it), Tb(it)
        kB, MB, GB, TB

    Note that the SI unit system does not support capital letter 'K'

    :param text: String input for bytes size conversion.
    :param unit_system: Unit system for byte size conversion.
    :param return_int: If True, returns integer representation of text
                       in bytes. (default: decimal)
    :returns: Numerical representation of text in bytes.
    :raises ValueError: If text has an invalid value.

    """
    try:
        base, reg_ex = UNIT_SYSTEM_INFO[unit_system]
    except KeyError:
        msg = _('Invalid unit system: "%s"') % unit_system
        raise ValueError(msg)
    match = reg_ex.match(text)
    if match:
        magnitude = float(match.group(1))
        unit_prefix = match.group(2)
        if match.group(3) in ['b', 'bit']:
            magnitude /= 8
    else:
        msg = _('Invalid string format: %s') % text
        raise ValueError(msg)
    if not unit_prefix:
        res = magnitude
    else:
        res = magnitude * pow(base, UNIT_PREFIX_EXPONENT[unit_prefix])
    if return_int:
        return int(math.ceil(res))
    return res
예제 #5
0
 def __init__(self, requested, permitted):
     msg = _("Length of %(given)d is too long, max = %(maximum)d")
     message = msg % {'given': requested, 'maximum': permitted}
     super(CryptoutilsException, self).__init__(message)
예제 #6
0
def main():
    usage = "usage: %prog [options] name [-l | target message]"
    parser = optparse.OptionParser(usage=usage)

    parser.add_option("-v",
                      "--verbose",
                      dest="verbose",
                      help=u._("Be verbose."),
                      action="store_true",
                      default=False)

    parser.add_option('--kite_host',
                      help=u._('Kite server host address.'),
                      default="localhost"),

    parser.add_option('--kite_port',
                      help=u._('Kite server port number.'),
                      default="9109"),

    parser.add_option('--key', "-k", help=u._('Optional base64 encoded key.')),

    parser.add_option('--queue',
                      "-q",
                      help=u._('Message queue url.'),
                      default="rabbit://localhost"),

    parser.add_option('--listen',
                      "-l",
                      help=u._('Listen for incoming messages.'),
                      action="store_true",
                      default=False),

    (options, args) = parser.parse_args()

    if not args:
        parser.print_usage()
        return -1

    # NOTE(tkelsey): using developer interface to remove the need to run
    # a keystone server.
    name = args[0]
    host = options.kite_host
    port = options.kite_port
    kite = "http://%s:%s/v1" % (host, port)
    auth = token_endpoint.Token(kite, 'aToken')

    transport_obj = transport.Transport(target=name, url=options.queue)
    session_obj = session.Session(auth=auth)
    client_obj = client.KiteClient(name,
                                   transport_obj,
                                   key=options.key,
                                   session=session_obj,
                                   verbose=options.verbose)

    if options.listen:
        try:
            message = client_obj.recv()
            print(message)
        except KeyboardInterrupt:
            pass

    else:
        if len(args) < 3:
            print("target and message are required when not listening")
            parser.print_usage()
            return -1

        else:
            targ = args[1]
            body = args[2]
            resp = client_obj.send(body, targ)
            print(resp)
예제 #7
0
 def __init__(self, requested, permitted):
     msg = _("Length of %(given)d is too long, max = %(maximum)d")
     message = msg % {'given': requested, 'maximum': permitted}
     super(CryptoutilsException, self).__init__(message)
예제 #8
0
class CryptoutilsException(Exception):
    """Generic Exception for Crypto utilities."""

    message = _("An unknown error occurred in crypto utils.")
예제 #9
0
def main():
    usage = "usage: %prog [options] name [-l | target message]"
    parser = optparse.OptionParser(usage=usage)

    parser.add_option("-v", "--verbose", dest="verbose",
                      help=u._("Be verbose."), action="store_true",
                      default=False)

    parser.add_option('--kite_host',
                      help=u._('Kite server host address.'),
                      default="localhost"),

    parser.add_option('--kite_port',
                      help=u._('Kite server port number.'),
                      default="9109"),

    parser.add_option('--key', "-k",
                      help=u._('Optional base64 encoded key.')),

    parser.add_option('--queue', "-q",
                      help=u._('Message queue url.'),
                      default="rabbit://localhost"),

    parser.add_option('--listen', "-l",
                      help=u._('Listen for incoming messages.'),
                      action="store_true", default=False),

    (options, args) = parser.parse_args()

    if not args:
        parser.print_usage()
        return -1

    # NOTE(tkelsey): using developer interface to remove the need to run
    # a keystone server.
    name = args[0]
    host = options.kite_host
    port = options.kite_port
    kite = "http://%s:%s/v1" % (host, port)
    auth = token_endpoint.Token(kite, 'aToken')

    transport_obj = transport.Transport(target=name, url=options.queue)
    session_obj = session.Session(auth=auth)
    client_obj = client.KiteClient(name, transport_obj,
                                   key=options.key,
                                   session=session_obj,
                                   verbose=options.verbose)

    if options.listen:
        try:
            message = client_obj.recv()
            print(message)
        except KeyboardInterrupt:
            pass

    else:
        if len(args) < 3:
            print("target and message are required when not listening")
            parser.print_usage()
            return -1

        else:
            targ = args[1]
            body = args[2]
            resp = client_obj.send(body, targ)
            print(resp)