def bool_from_string(subject, strict=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 is considered False. 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, basestring): subject = str(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 False
def to_bytes(text, default=0): """Try to turn a string into a number of bytes. Looks at the last characters of the text to determine what conversion is needed to turn the input text into a byte number. Supports: B/b, K/k, M/m, G/g, T/t (or the same with b/B on the end) """ # Take off everything not number 'like' (which should leave # only the byte 'identifier' left) mult_key_org = text.lstrip("-1234567890") mult_key = mult_key_org.lower() mult_key_len = len(mult_key) if mult_key.endswith("b"): mult_key = mult_key[0:-1] try: multiplier = BYTE_MULTIPLIERS[mult_key] if mult_key_len: # Empty cases shouldn't cause text[0:-0] text = text[0:-mult_key_len] return int(text) * multiplier except KeyError: msg = _("Unknown byte multiplier: %s") % mult_key_org raise TypeError(msg) except ValueError: return default