def process_control_chars(string, strategy='replace'): '''Look for and transform :term:`control characters` in a string :arg string: string to search for and transform :term:`control characters` within :kwarg strategy: XML does not allow :term:`ASCII` :term:`control characters`. When we encounter those we need to know what to do. Valid options are: :replace: (default) Replace the :term:`control characters` with ``"?"`` :ignore: Remove the characters altogether from the output :strict: Raise a :exc:`~kitchen.text.exceptions.ControlCharError` when we encounter a control character :raises TypeError: if :attr:`string` is not a unicode string. :raises ValueError: if the strategy is not one of replace, ignore, or strict. :raises kitchen.text.exceptions.ControlCharError: if the strategy is ``strict`` and a :term:`control character` is present in the :attr:`string` :returns: :class:`unicode` string with no :term:`control characters` in it. ''' if not isinstance(string, unicode): raise TypeError( k.b_('process_control_char must have a unicode type as' ' the first argument.')) if strategy == 'ignore': control_table = dict(zip(_CONTROL_CODES, [None] * len(_CONTROL_CODES))) elif strategy == 'replace': control_table = dict(zip(_CONTROL_CODES, [u'?'] * len(_CONTROL_CODES))) elif strategy == 'strict': control_table = None # Test that there are no control codes present data = frozenset(string) if [c for c in _CONTROL_CHARS if c in data]: raise ControlCharError( k.b_('ASCII control code present in string' ' input')) else: raise ValueError( k.b_('The strategy argument to process_control_chars' ' must be one of ignore, replace, or strict')) if control_table: string = string.translate(control_table) return string
def utf8_width_chop(msg, chop=None): '''**Deprecated** Return a string chopped to a given :term:`textual width` Use :func:`~kitchen.text.display.textual_width_chop` and :func:`~kitchen.text.display.textual_width` instead:: >>> msg = 'く ku ら ra と to み mi' >>> # Old way: >>> utf8_width_chop(msg, 5) (5, 'く ku') >>> # New way >>> from kitchen.text.converters import to_bytes >>> from kitchen.text.display import textual_width, textual_width_chop >>> (textual_width(msg), to_bytes(textual_width_chop(msg, 5))) (5, 'く ku') ''' warnings.warn(b_('kitchen.text.utf8.utf8_width_chop is deprecated. Use' ' kitchen.text.display.textual_width_chop instead'), DeprecationWarning, stacklevel=2) if chop == None: return textual_width(msg), msg as_bytes = not isinstance(msg, unicode) chopped_msg = textual_width_chop(msg, chop) if as_bytes: chopped_msg = to_bytes(chopped_msg) return textual_width(chopped_msg), chopped_msg
def to_xml(string, encoding='utf-8', attrib=False, control_chars='ignore'): '''*Deprecated*: Use :func:`guess_encoding_to_xml` instead ''' warnings.warn(k.b_('kitchen.text.converters.to_xml is deprecated. Use' ' kitchen.text.converters.guess_encoding_to_xml instead.'), DeprecationWarning, stacklevel=2) return guess_encoding_to_xml(string, output_encoding=encoding, attrib=attrib, control_chars=control_chars)
def process_control_chars(string, strategy='replace'): '''Look for and transform :term:`control characters` in a string :arg string: string to search for and transform :term:`control characters` within :kwarg strategy: XML does not allow :term:`ASCII` :term:`control characters`. When we encounter those we need to know what to do. Valid options are: :replace: (default) Replace the :term:`control characters` with ``"?"`` :ignore: Remove the characters altogether from the output :strict: Raise a :exc:`~kitchen.text.exceptions.ControlCharError` when we encounter a control character :raises TypeError: if :attr:`string` is not a unicode string. :raises ValueError: if the strategy is not one of replace, ignore, or strict. :raises kitchen.text.exceptions.ControlCharError: if the strategy is ``strict`` and a :term:`control character` is present in the :attr:`string` :returns: :class:`unicode` string with no :term:`control characters` in it. ''' if not isinstance(string, unicode): raise TypeError(k.b_('process_control_char must have a unicode type as' ' the first argument.')) if strategy == 'ignore': control_table = dict(zip(_CONTROL_CODES, [None] * len(_CONTROL_CODES))) elif strategy == 'replace': control_table = dict(zip(_CONTROL_CODES, [u'?'] * len(_CONTROL_CODES))) elif strategy == 'strict': control_table = None # Test that there are no control codes present data = frozenset(string) if [c for c in _CONTROL_CHARS if c in data]: raise ControlCharError(k.b_('ASCII control code present in string' ' input')) else: raise ValueError(k.b_('The strategy argument to process_control_chars' ' must be one of ignore, replace, or strict')) if control_table: string = string.translate(control_table) return string
def _utf8_width_le(width, *args): '''**Deprecated** Convert the arguments to unicode and use :func:`kitchen.text.display._textual_width_le` instead. ''' warnings.warn(b_('kitchen.text.utf8._utf8_width_le is deprecated. Use' ' kitchen.text.display._textual_width_le instead'), DeprecationWarning, stacklevel=2) # This assumes that all args. are utf8. return _textual_width_le(width, to_unicode(''.join(args)))
def utf8_width(msg): '''**Deprecated** Get the :term:`textual width` of a :term:`utf-8` string Use :func:`kitchen.text.display.textual_width` instead. ''' warnings.warn(b_('kitchen.text.utf8.utf8_width is deprecated. Use' ' kitchen.text.display.textual_width(msg) instead'), DeprecationWarning, stacklevel=2) return textual_width(msg)
def utf8_valid(msg): '''**Deprecated** Detect if a string is valid :term:`utf-8` Use :func:`kitchen.text.misc.byte_string_valid_encoding` instead. ''' warnings.warn(b_('kitchen.text.utf8.utf8_valid is deprecated. Use' ' kitchen.text.misc.byte_string_valid_encoding(msg) instead'), DeprecationWarning, stacklevel=2) return byte_string_valid_encoding(msg)
def utf8_text_fill(text, *args, **kwargs): '''**Deprecated** Similar to :func:`textwrap.fill` but understands :term:`utf-8` strings and doesn't screw up lists/blocks/etc. Use :func:`kitchen.text.display.fill` instead. ''' warnings.warn(b_('kitchen.text.utf8.utf8_text_fill is deprecated. Use' ' kitchen.text.display.fill instead'), DeprecationWarning, stacklevel=2) # This assumes that all args. are utf8. return fill(text, *args, **kwargs)
def utf8_width_fill(msg, fill, chop=None, left=True, prefix='', suffix=''): '''**Deprecated** Pad a :term:`utf-8` string to fill a specified width Use :func:`~kitchen.text.display.byte_string_textual_width_fill` instead ''' warnings.warn(b_('kitchen.text.utf8.utf8_width_fill is deprecated. Use' ' kitchen.text.display.byte_string_textual_width_fill instead'), DeprecationWarning, stacklevel=2) return byte_string_textual_width_fill(msg, fill, chop=chop, left=left, prefix=prefix, suffix=suffix)
def utf8_valid(msg): '''**Deprecated** Detect if a string is valid :term:`utf-8` Use :func:`kitchen.text.misc.byte_string_valid_encoding` instead. ''' warnings.warn(b_( 'kitchen.text.utf8.utf8_valid is deprecated. Use' ' kitchen.text.misc.byte_string_valid_encoding(msg) instead'), DeprecationWarning, stacklevel=2) return byte_string_valid_encoding(msg)
def to_utf8(obj, errors='replace', non_string='passthru'): '''*Deprecated* Convert :class:`unicode` to an encoded :term:`utf-8` byte :class:`str`. You should be using :func:`to_bytes` instead:: to_bytes(obj, encoding='utf-8', non_string='passthru') ''' warnings.warn(k.b_('kitchen.text.converters.to_utf8 is deprecated. Use' ' kitchen.text.converters.to_bytes(obj, encoding="utf-8",' ' nonstring="passthru" instead.'), DeprecationWarning, stacklevel=2) return to_bytes(obj, encoding='utf-8', errors=errors, nonstring=non_string)
def utf8_width_fill(msg, fill, chop=None, left=True, prefix='', suffix=''): '''**Deprecated** Pad a :term:`utf-8` string to fill a specified width Use :func:`~kitchen.text.display.byte_string_textual_width_fill` instead ''' warnings.warn(b_( 'kitchen.text.utf8.utf8_width_fill is deprecated. Use' ' kitchen.text.display.byte_string_textual_width_fill instead'), DeprecationWarning, stacklevel=2) return byte_string_textual_width_fill(msg, fill, chop=chop, left=left, prefix=prefix, suffix=suffix)
def html_entities_unescape(string): '''Substitute unicode characters for HTML entities :arg string: :class:`unicode` string to substitute out html entities :raises TypeError: if something other than a :class:`unicode` string is given :rtype: :class:`unicode` string :returns: The plain text without html entities ''' def fixup(match): string = match.group(0) if string[:1] == u"<": return "" # ignore tags if string[:2] == u"&#": try: if string[:3] == u"&#x": return unichr(int(string[3:-1], 16)) else: return unichr(int(string[2:-1])) except ValueError: # If the value is outside the unicode codepoint range, leave # it in the output as is pass elif string[:1] == u"&": entity = htmlentitydefs.entitydefs.get( string[1:-1].encode('utf-8')) if entity: if entity[:2] == "&#": try: return unichr(int(entity[2:-1])) except ValueError: # If the value is outside the unicode codepoint range, # leave it in the output as is pass else: return unicode(entity, "iso-8859-1") return string # leave as is if not isinstance(string, unicode): raise TypeError( k.b_('html_entities_unescape must have a unicode type' ' for its first argument')) return re.sub(_ENTITY_RE, fixup, string)
def utf8_text_wrap(text, width=70, initial_indent='', subsequent_indent=''): '''**Deprecated** Similar to :func:`textwrap.wrap` but understands :term:`utf-8` data and doesn't screw up lists/blocks/etc Use :func:`kitchen.text.display.wrap` instead ''' warnings.warn(b_('kitchen.text.utf8.utf8_text_wrap is deprecated. Use' ' kitchen.text.display.wrap instead'), DeprecationWarning, stacklevel=2) as_bytes = not isinstance(text, unicode) text = to_unicode(text) lines = wrap(text, width=width, initial_indent=initial_indent, subsequent_indent=subsequent_indent) if as_bytes: lines = [to_bytes(m) for m in lines] return lines
def html_entities_unescape(string): '''Substitute unicode characters for HTML entities :arg string: :class:`unicode` string to substitute out html entities :raises TypeError: if something other than a :class:`unicode` string is given :rtype: :class:`unicode` string :returns: The plain text without html entities ''' def fixup(match): string = match.group(0) if string[:1] == u"<": return "" # ignore tags if string[:2] == u"&#": try: if string[:3] == u"&#x": return unichr(int(string[3:-1], 16)) else: return unichr(int(string[2:-1])) except ValueError: # If the value is outside the unicode codepoint range, leave # it in the output as is pass elif string[:1] == u"&": entity = htmlentitydefs.entitydefs.get(string[1:-1].encode('utf-8')) if entity: if entity[:2] == "&#": try: return unichr(int(entity[2:-1])) except ValueError: # If the value is outside the unicode codepoint range, # leave it in the output as is pass else: return unicode(entity, "iso-8859-1") return string # leave as is if not isinstance(string, unicode): raise TypeError(k.b_('html_entities_unescape must have a unicode type' ' for its first argument')) return re.sub(_ENTITY_RE, fixup, string)
def guess_encoding(byte_string, disable_chardet=False): '''Try to guess the encoding of a byte :class:`str` :arg byte_string: byte :class:`str` to guess the encoding of :kwarg disable_chardet: If this is True, we never attempt to use :mod:`chardet` to guess the encoding. This is useful if you need to have reproducibility whether :mod:`chardet` is installed or not. Default: :data:`False`. :raises TypeError: if :attr:`byte_string` is not a byte :class:`str` type :returns: string containing a guess at the encoding of :attr:`byte_string`. This is appropriate to pass as the encoding argument when encoding and decoding unicode strings. We start by attempting to decode the byte :class:`str` as :term:`UTF-8`. If this succeeds we tell the world it's :term:`UTF-8` text. If it doesn't and :mod:`chardet` is installed on the system and :attr:`disable_chardet` is False this function will use it to try detecting the encoding of :attr:`byte_string`. If it is not installed or :mod:`chardet` cannot determine the encoding with a high enough confidence then we rather arbitrarily claim that it is ``latin-1``. Since ``latin-1`` will encode to every byte, decoding from ``latin-1`` to :class:`unicode` will not cause :exc:`UnicodeErrors` although the output might be mangled. ''' if not isinstance(byte_string, str): raise TypeError(k.b_('byte_string must be a byte string (str)')) input_encoding = 'utf-8' try: unicode(byte_string, input_encoding, 'strict') except UnicodeDecodeError: input_encoding = None if not input_encoding and chardet and not disable_chardet: detection_info = chardet.detect(byte_string) if detection_info['confidence'] >= _CHARDET_THRESHHOLD: input_encoding = detection_info['encoding'] if not input_encoding: input_encoding = 'latin-1' return input_encoding
def to_str(obj): '''*Deprecated* This function converts something to a byte :class:`str` if it isn't one. It's used to call :func:`str` or :func:`unicode` on the object to get its simple representation without danger of getting a :exc:`UnicodeError`. You should be using :func:`to_unicode` or :func:`to_bytes` explicitly instead. If you need :class:`unicode` strings:: to_unicode(obj, nonstring='simplerepr') If you need byte :class:`str`:: to_bytes(obj, nonstring='simplerepr') ''' warnings.warn(k.b_('to_str is deprecated. Use to_unicode or to_bytes' ' instead. See the to_str docstring for' ' porting information.'), DeprecationWarning, stacklevel=2) return to_bytes(obj, nonstring='simplerepr')
def __init__(self, default_factory=None, *args, **kwargs): if (default_factory is not None and not hasattr(default_factory, '__call__')): raise TypeError(b_('First argument must be callable')) dict.__init__(self, *args, **kwargs) self.default_factory = default_factory
def _ucp_width(ucs, control_chars='guess'): '''Get the :term:`textual width` of a ucs character :arg ucs: integer representing a single unicode :term:`code point` :kwarg control_chars: specify how to deal with :term:`control characters`. Possible values are: :guess: (default) will take a guess for :term:`control character` widths. Most codes will return zero width. ``backspace``, ``delete``, and ``clear delete`` return -1. ``escape`` currently returns -1 as well but this is not guaranteed as it's not always correct :strict: will raise :exc:`~kitchen.text.exceptions.ControlCharError` if a :term:`control character` is encountered :raises ControlCharError: if the :term:`code point` is a unicode :term:`control character` and :attr:`control_chars` is set to 'strict' :returns: :term:`textual width` of the character. .. note:: It's important to remember this is :term:`textual width` and not the number of characters or bytes. ''' # test for 8-bit control characters if ucs < 32 or (ucs < 0xa0 and ucs >= 0x7f): # Control character detected if control_chars == 'strict': raise ControlCharError( b_('_ucp_width does not understand how to' ' assign a width value to control characters.')) if ucs in (0x08, 0x07F, 0x94): # Backspace, delete, and clear delete remove a single character return -1 if ucs == 0x1b: # Excape is tricky. It removes some number of characters that # come after it but the amount is dependent on what is # interpreting the code. # So this is going to often be wrong but other values will be # wrong as well. return -1 # All other control characters get 0 width return 0 if _interval_bisearch(ucs, _COMBINING): # Combining characters return 0 width as they will be combined with # the width from other characters return 0 # if we arrive here, ucs is not a combining or C0/C1 control character return (1 + ( ucs >= 0x1100 and (ucs <= 0x115f or # Hangul Jamo init. consonants ucs == 0x2329 or ucs == 0x232a or (ucs >= 0x2e80 and ucs <= 0xa4cf and ucs != 0x303f) or # CJK ... Yi (ucs >= 0xac00 and ucs <= 0xd7a3) or # Hangul Syllables (ucs >= 0xf900 and ucs <= 0xfaff) or # CJK Compatibility Ideographs (ucs >= 0xfe10 and ucs <= 0xfe19) or # Vertical forms (ucs >= 0xfe30 and ucs <= 0xfe6f) or # CJK Compatibility Forms (ucs >= 0xff00 and ucs <= 0xff60) or # Fullwidth Forms (ucs >= 0xffe0 and ucs <= 0xffe6) or (ucs >= 0x20000 and ucs <= 0x2fffd) or (ucs >= 0x30000 and ucs <= 0x3fffd))))
def _ucp_width(ucs, control_chars='guess'): '''Get the :term:`textual width` of a ucs character :arg ucs: integer representing a single unicode :term:`code point` :kwarg control_chars: specify how to deal with :term:`control characters`. Possible values are: :guess: (default) will take a guess for :term:`control character` widths. Most codes will return zero width. ``backspace``, ``delete``, and ``clear delete`` return -1. ``escape`` currently returns -1 as well but this is not guaranteed as it's not always correct :strict: will raise :exc:`~kitchen.text.exceptions.ControlCharError` if a :term:`control character` is encountered :raises ControlCharError: if the :term:`code point` is a unicode :term:`control character` and :attr:`control_chars` is set to 'strict' :returns: :term:`textual width` of the character. .. note:: It's important to remember this is :term:`textual width` and not the number of characters or bytes. ''' # test for 8-bit control characters if ucs < 32 or (ucs < 0xa0 and ucs >= 0x7f): # Control character detected if control_chars == 'strict': raise ControlCharError(b_('_ucp_width does not understand how to' ' assign a width value to control characters.')) if ucs in (0x08, 0x07F, 0x94): # Backspace, delete, and clear delete remove a single character return -1 if ucs == 0x1b: # Excape is tricky. It removes some number of characters that # come after it but the amount is dependent on what is # interpreting the code. # So this is going to often be wrong but other values will be # wrong as well. return -1 # All other control characters get 0 width return 0 if _interval_bisearch(ucs, _COMBINING): # Combining characters return 0 width as they will be combined with # the width from other characters return 0 # if we arrive here, ucs is not a combining or C0/C1 control character return (1 + (ucs >= 0x1100 and (ucs <= 0x115f or # Hangul Jamo init. consonants ucs == 0x2329 or ucs == 0x232a or (ucs >= 0x2e80 and ucs <= 0xa4cf and ucs != 0x303f) or # CJK ... Yi (ucs >= 0xac00 and ucs <= 0xd7a3) or # Hangul Syllables (ucs >= 0xf900 and ucs <= 0xfaff) or # CJK Compatibility Ideographs (ucs >= 0xfe10 and ucs <= 0xfe19) or # Vertical forms (ucs >= 0xfe30 and ucs <= 0xfe6f) or # CJK Compatibility Forms (ucs >= 0xff00 and ucs <= 0xff60) or # Fullwidth Forms (ucs >= 0xffe0 and ucs <= 0xffe6) or (ucs >= 0x20000 and ucs <= 0x2fffd) or (ucs >= 0x30000 and ucs <= 0x3fffd))))
def byte_string_to_xml(byte_string, input_encoding='utf-8', errors='replace', output_encoding='utf-8', attrib=False, control_chars='replace'): '''Make sure a byte :class:`str` is validly encoded for xml output :arg byte_string: Byte :class:`str` to turn into valid xml output :kwarg input_encoding: Encoding of :attr:`byte_string`. Default ``utf-8`` :kwarg errors: How to handle errors encountered while decoding the :attr:`byte_string` into :class:`unicode` at the beginning of the process. Values are: :replace: (default) Replace the invalid bytes with a ``?`` :ignore: Remove the characters altogether from the output :strict: Raise an :exc:`UnicodeDecodeError` when we encounter a non-decodable character :kwarg output_encoding: Encoding for the xml file that this string will go into. Default is ``utf-8``. If all the characters in :attr:`byte_string` are not encodable in this encoding, the unknown characters will be entered into the output string using xml character references. :kwarg attrib: If :data:`True`, quote the string for use in an xml attribute. If :data:`False` (default), quote for use in an xml text field. :kwarg control_chars: XML does not allow :term:`control characters`. When we encounter those we need to know what to do. Valid options are: :replace: (default) Replace the :term:`control characters` with ``?`` :ignore: Remove the characters altogether from the output :strict: Raise an error when we encounter a :term:`control character` :raises XmlEncodeError: If :attr:`control_chars` is set to ``strict`` and the string to be made suitable for output to xml contains :term:`control characters` then we raise this exception. :raises UnicodeDecodeError: If errors is set to ``strict`` and the :attr:`byte_string` contains bytes that are not decodable using :attr:`input_encoding`, this error is raised :rtype: byte :class:`str` :returns: representation of the byte :class:`str` in the output encoding with any bytes that aren't available in xml taken care of. Use this when you have a byte :class:`str` representing text that you need to make suitable for output to xml. There are several cases where this is the case. For instance, if you need to transform some strings encoded in ``latin-1`` to :term:`utf-8` for output:: utf8_string = byte_string_to_xml(latin1_string, input_encoding='latin-1') If you already have strings in the proper encoding you may still want to use this function to remove :term:`control characters`:: cleaned_string = byte_string_to_xml(string, input_encoding='utf-8', output_encoding='utf-8') .. seealso:: :func:`unicode_to_xml` for other ideas on using this function ''' if not isinstance(byte_string, str): raise XmlEncodeError(k.b_('byte_string_to_xml can only take a byte' ' string as its first argument. Use unicode_to_xml for' ' unicode strings')) # Decode the string into unicode u_string = unicode(byte_string, input_encoding, errors) return unicode_to_xml(u_string, encoding=output_encoding, attrib=attrib, control_chars=control_chars)
def to_unicode(obj, encoding='utf-8', errors='replace', nonstring=None, non_string=None): '''Convert an object into a :class:`unicode` string :arg obj: Object to convert to a :class:`unicode` string. This should normally be a byte :class:`str` :kwarg encoding: What encoding to try converting the byte :class:`str` as. Defaults to :term:`utf-8` :kwarg errors: If errors are found while decoding, perform this action. Defaults to ``replace`` which replaces the invalid bytes with a character that means the bytes were unable to be decoded. Other values are the same as the error handling schemes in the `codec base classes <http://docs.python.org/library/codecs.html#codec-base-classes>`_. For instance ``strict`` which raises an exception and ``ignore`` which simply omits the non-decodable characters. :kwarg nonstring: How to treat nonstring values. Possible values are: :simplerepr: Attempt to call the object's "simple representation" method and return that value. Python-2.3+ has two methods that try to return a simple representation: :meth:`object.__unicode__` and :meth:`object.__str__`. We first try to get a usable value from :meth:`object.__unicode__`. If that fails we try the same with :meth:`object.__str__`. :empty: Return an empty :class:`unicode` string :strict: Raise a :exc:`TypeError` :passthru: Return the object unchanged :repr: Attempt to return a :class:`unicode` string of the repr of the object Default is ``simplerepr`` :kwarg non_string: *Deprecated* Use :attr:`nonstring` instead :raises TypeError: if :attr:`nonstring` is ``strict`` and a non-:class:`basestring` object is passed in or if :attr:`nonstring` is set to an unknown value :raises UnicodeDecodeError: if :attr:`errors` is ``strict`` and :attr:`obj` is not decodable using the given encoding :returns: :class:`unicode` string or the original object depending on the value of :attr:`nonstring`. Usually this should be used on a byte :class:`str` but it can take both byte :class:`str` and :class:`unicode` strings intelligently. Nonstring objects are handled in different ways depending on the setting of the :attr:`nonstring` parameter. The default values of this function are set so as to always return a :class:`unicode` string and never raise an error when converting from a byte :class:`str` to a :class:`unicode` string. However, when you do not pass validly encoded text (or a nonstring object), you may end up with output that you don't expect. Be sure you understand the requirements of your data, not just ignore errors by passing it through this function. .. versionchanged:: 0.2.1a2 Deprecated :attr:`non_string` in favor of :attr:`nonstring` parameter and changed default value to ``simplerepr`` ''' if isinstance(obj, basestring): if isinstance(obj, unicode): return obj if encoding in _UTF8_ALIASES: return unicode(obj, 'utf-8', errors) if encoding in _LATIN1_ALIASES: return unicode(obj, 'latin-1', errors) return obj.decode(encoding, errors) if non_string: warnings.warn(k.b_('non_string is a deprecated parameter of' ' to_unicode(). Use nonstring instead'), DeprecationWarning, stacklevel=2) if not nonstring: nonstring = non_string if not nonstring: nonstring = 'simplerepr' if nonstring == 'empty': return u'' elif nonstring == 'passthru': return obj elif nonstring == 'simplerepr': try: simple = obj.__unicode__() except (AttributeError, UnicodeError): simple = None if not simple: try: simple = str(obj) except UnicodeError: try: simple = obj.__str__() except (UnicodeError, AttributeError): simple = u'' if not isinstance(simple, unicode): return unicode(simple, encoding, errors) return simple elif nonstring in ('repr', 'strict'): obj_repr = repr(obj) if not isinstance(obj_repr, unicode): obj_repr = unicode(obj_repr, encoding, errors) if nonstring == 'repr': return obj_repr raise TypeError(k.b_('to_unicode was given "%(obj)s" which is neither' ' a byte string (str) or a unicode string') % {'obj': obj_repr.encode(encoding, 'replace')}) raise TypeError(k.b_('nonstring value, %(param)s, is not set to a valid' ' action') % {'param': nonstring})
def unicode_to_xml(string, encoding='utf-8', attrib=False, control_chars='replace'): '''Take a :class:`unicode` string and turn it into a byte :class:`str` suitable for xml :arg string: :class:`unicode` string to encode into an XML compatible byte :class:`str` :kwarg encoding: encoding to use for the returned byte :class:`str`. Default is to encode to :term:`UTF-8`. If some of the characters in :attr:`string` are not encodable in this encoding, the unknown characters will be entered into the output string using xml character references. :kwarg attrib: If :data:`True`, quote the string for use in an xml attribute. If :data:`False` (default), quote for use in an xml text field. :kwarg control_chars: :term:`control characters` are not allowed in XML documents. When we encounter those we need to know what to do. Valid options are: :replace: (default) Replace the control characters with ``?`` :ignore: Remove the characters altogether from the output :strict: Raise an :exc:`~kitchen.text.exceptions.XmlEncodeError` when we encounter a :term:`control character` :raises kitchen.text.exceptions.XmlEncodeError: If :attr:`control_chars` is set to ``strict`` and the string to be made suitable for output to xml contains :term:`control characters` or if :attr:`string` is not a :class:`unicode` string then we raise this exception. :raises ValueError: If :attr:`control_chars` is set to something other than ``replace``, ``ignore``, or ``strict``. :rtype: byte :class:`str` :returns: representation of the :class:`unicode` string as a valid XML byte :class:`str` XML files consist mainly of text encoded using a particular charset. XML also denies the use of certain bytes in the encoded text (example: ``ASCII Null``). There are also special characters that must be escaped if they are present in the input (example: ``<``). This function takes care of all of those issues for you. There are a few different ways to use this function depending on your needs. The simplest invocation is like this:: unicode_to_xml(u'String with non-ASCII characters: <"á と">') This will return the following to you, encoded in :term:`utf-8`:: 'String with non-ASCII characters: <"á と">' Pretty straightforward. Now, what if you need to encode your document in something other than :term:`utf-8`? For instance, ``latin-1``? Let's see:: unicode_to_xml(u'String with non-ASCII characters: <"á と">', encoding='latin-1') 'String with non-ASCII characters: <"á と">' Because the ``と`` character is not available in the ``latin-1`` charset, it is replaced with ``と`` in our output. This is an xml character reference which represents the character at unicode codepoint ``12392``, the ``と`` character. When you want to reverse this, use :func:`xml_to_unicode` which will turn a byte :class:`str` into a :class:`unicode` string and replace the xml character references with the unicode characters. XML also has the quirk of not allowing :term:`control characters` in its output. The :attr:`control_chars` parameter allows us to specify what to do with those. For use cases that don't need absolute character by character fidelity (example: holding strings that will just be used for display in a GUI app later), the default value of ``replace`` works well:: unicode_to_xml(u'String with disallowed control chars: \u0000\u0007') 'String with disallowed control chars: ??' If you do need to be able to reproduce all of the characters at a later date (examples: if the string is a key value in a database or a path on a filesystem) you have many choices. Here are a few that rely on ``utf-7``, a verbose encoding that encodes :term:`control characters` (as well as non-:term:`ASCII` unicode values) to characters from within the :term:`ASCII` printable characters. The good thing about doing this is that the code is pretty simple. You just need to use ``utf-7`` both when encoding the field for xml and when decoding it for use in your python program:: unicode_to_xml(u'String with unicode: と and control char: \u0007', encoding='utf7') 'String with unicode: +MGg and control char: +AAc-' # [...] xml_to_unicode('String with unicode: +MGg and control char: +AAc-', encoding='utf7') u'String with unicode: と and control char: \u0007' As you can see, the ``utf-7`` encoding will transform even characters that would be representable in :term:`utf-8`. This can be a drawback if you want unicode characters in the file to be readable without being decoded first. You can work around this with increased complexity in your application code:: encoding = 'utf-8' u_string = u'String with unicode: と and control char: \u0007' try: # First attempt to encode to utf8 data = unicode_to_xml(u_string, encoding=encoding, errors='strict') except XmlEncodeError: # Fallback to utf-7 encoding = 'utf-7' data = unicode_to_xml(u_string, encoding=encoding, errors='strict') write_tag('<mytag encoding=%s>%s</mytag>' % (encoding, data)) # [...] encoding = tag.attributes.encoding u_string = xml_to_unicode(u_string, encoding=encoding) Using code similar to that, you can have some fields encoded using your default encoding and fallback to ``utf-7`` if there are :term:`control characters` present. .. note:: If your goal is to preserve the :term:`control characters` you cannot save the entire file as ``utf-7`` and set the xml encoding parameter to ``utf-7`` if your goal is to preserve the :term:`control characters`. Because XML doesn't allow :term:`control characters`, you have to encode those separate from any encoding work that the XML parser itself knows about. .. seealso:: :func:`bytes_to_xml` if you're dealing with bytes that are non-text or of an unknown encoding that you must preserve on a byte for byte level. :func:`guess_encoding_to_xml` if you're dealing with strings in unknown encodings that you don't need to save with char-for-char fidelity. ''' if not string: # Small optimization return '' try: process_control_chars(string, strategy=control_chars) except TypeError: raise XmlEncodeError(k.b_('unicode_to_xml must have a unicode type as' ' the first argument. Use bytes_string_to_xml for byte' ' strings.')) except ValueError: raise ValueError(k.b_('The control_chars argument to unicode_to_xml' ' must be one of ignore, replace, or strict')) except ControlCharError, exc: raise XmlEncodeError(exc.args[0])
def to_bytes(obj, encoding='utf-8', errors='replace', nonstring=None, non_string=None): '''Convert an object into a byte :class:`str` :arg obj: Object to convert to a byte :class:`str`. This should normally be a :class:`unicode` string. :kwarg encoding: Encoding to use to convert the :class:`unicode` string into a byte :class:`str`. Defaults to :term:`utf-8`. :kwarg errors: If errors are found while encoding, perform this action. Defaults to ``replace`` which replaces the invalid bytes with a character that means the bytes were unable to be encoded. Other values are the same as the error handling schemes in the `codec base classes <http://docs.python.org/library/codecs.html#codec-base-classes>`_. For instance ``strict`` which raises an exception and ``ignore`` which simply omits the non-encodable characters. :kwarg nonstring: How to treat nonstring values. Possible values are: :simplerepr: Attempt to call the object's "simple representation" method and return that value. Python-2.3+ has two methods that try to return a simple representation: :meth:`object.__unicode__` and :meth:`object.__str__`. We first try to get a usable value from :meth:`object.__str__`. If that fails we try the same with :meth:`object.__unicode__`. :empty: Return an empty byte :class:`str` :strict: Raise a :exc:`TypeError` :passthru: Return the object unchanged :repr: Attempt to return a byte :class:`str` of the :func:`repr` of the object Default is ``simplerepr``. :kwarg non_string: *Deprecated* Use :attr:`nonstring` instead. :raises TypeError: if :attr:`nonstring` is ``strict`` and a non-:class:`basestring` object is passed in or if :attr:`nonstring` is set to an unknown value. :raises UnicodeEncodeError: if :attr:`errors` is ``strict`` and all of the bytes of :attr:`obj` are unable to be encoded using :attr:`encoding`. :returns: byte :class:`str` or the original object depending on the value of :attr:`nonstring`. .. warning:: If you pass a byte :class:`str` into this function the byte :class:`str` is returned unmodified. It is **not** re-encoded with the specified :attr:`encoding`. The easiest way to achieve that is:: to_bytes(to_unicode(text), encoding='utf-8') The initial :func:`to_unicode` call will ensure text is a :class:`unicode` string. Then, :func:`to_bytes` will turn that into a byte :class:`str` with the specified encoding. Usually, this should be used on a :class:`unicode` string but it can take either a byte :class:`str` or a :class:`unicode` string intelligently. Nonstring objects are handled in different ways depending on the setting of the :attr:`nonstring` parameter. The default values of this function are set so as to always return a byte :class:`str` and never raise an error when converting from unicode to bytes. However, when you do not pass an encoding that can validly encode the object (or a non-string object), you may end up with output that you don't expect. Be sure you understand the requirements of your data, not just ignore errors by passing it through this function. .. versionchanged:: 0.2.1a2 Deprecated :attr:`non_string` in favor of :attr:`nonstring` parameter and changed default value to ``simplerepr`` ''' if isinstance(obj, basestring): if isinstance(obj, str): return obj return obj.encode(encoding, errors) if non_string: warnings.warn(k.b_('non_string is a deprecated parameter of' ' to_bytes(). Use nonstring instead'), DeprecationWarning, stacklevel=2) if not nonstring: nonstring = non_string if not nonstring: nonstring = 'simplerepr' if nonstring == 'empty': return '' elif nonstring == 'passthru': return obj elif nonstring == 'simplerepr': try: simple = str(obj) except UnicodeError: try: simple = obj.__str__() except (AttributeError, UnicodeError): simple = None if not simple: try: simple = obj.__unicode__() except (AttributeError, UnicodeError): simple = '' if isinstance(simple, unicode): simple = simple.encode(encoding, 'replace') return simple elif nonstring in ('repr', 'strict'): try: obj_repr = obj.__repr__() except (AttributeError, UnicodeError): obj_repr = '' if isinstance(obj_repr, unicode): obj_repr = obj_repr.encode(encoding, errors) else: obj_repr = str(obj_repr) if nonstring == 'repr': return obj_repr raise TypeError(k.b_('to_bytes was given "%(obj)s" which is neither' ' a unicode string or a byte string (str)') % {'obj': obj_repr}) raise TypeError(k.b_('nonstring value, %(param)s, is not set to a valid' ' action') % {'param': nonstring})