예제 #1
0
파일: display.py 프로젝트: andelux/crawler
def _ucp_width(ucs, control_chars='guess'):
    '''Get the textual width of a ucs character.

    :arg ucs: integer representing a single unicode :term:`code point`
    :kwarg control_chars: specify how to deal with control chars.  Possible
        values are:
            :guess: (default) will take a guess for control code widths.  Most
                codes will return 0 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 control code is encountered
    :raises ControlCharError: if the :term:`code point` is a unicode
        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(
                _('_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))))
예제 #2
0
def utf8_width_chop(msg, chop=None):
    '''Deprecated

    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(_('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
예제 #3
0
def utf8_text_fill(text, *args, **kwargs):
    '''**Deprecated**  Use :func:`kitchen.text.display.fill` instead.'''
    warnings.warn(_('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)
예제 #4
0
def utf8_width(msg):
    '''Deprecated

    Use :func:`~kitchen.text.utf8.textual_width` instead.
    '''
    warnings.warn(_('kitchen.text.utf8.utf8_width is deprecated.  Use'
                    ' kitchen.text.display.textual_width(msg) instead'),
                  DeprecationWarning,
                  stacklevel=2)
    return textual_width(msg)
예제 #5
0
def _utf8_width_le(width, *args):
    '''**Deprecated** Convert the arguments to unicode and use
    :func:`kitchen.text.display._textual_width_le` instead.
    '''
    warnings.warn(_('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)))
예제 #6
0
def utf8_valid(msg):
    '''Deprecated.  Detect if a string is valid utf8.

    Use :func:`kitchen.text.misc.byte_string_valid_encoding` instead.
    '''
    warnings.warn(_(
        '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)
예제 #7
0
def to_xml(string, encoding='utf8', attrib=False, control_chars='ignore'):
    '''Deprecated: Use guess_encoding_to_xml() instead
    '''
    warnings.warn(_('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)
예제 #8
0
def process_control_chars(string, strategy='replace'):
    '''Look for and transform control characters in a string

    :arg string: string to search for and transform control characters in
    :kwarg strategy: XML does not allow ASCII control characters.  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 error 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.
    :returns: unicode string with no control characters in it.
    '''
    if not isinstance(string, unicode):
        raise TypeError(
            _('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(
                _('ASCII control code present in string'
                  ' input'))
    else:
        raise ValueError(
            _('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
예제 #9
0
def to_utf8(obj, errors='replace', non_string='passthru'):
    '''Deprecated.  Use to_bytes(obj, encoding='utf8', non_string='passthru')

    Convert 'unicode' to an encoded utf-8 byte string
    '''
    warnings.warn(_('kitchen.text.converters.to_utf8 is deprecated.  Use'
                    ' kitchen.text.converters.to_bytes(obj, encoding="utf8",'
                    ' non_string="passthru" instead.'),
                  DeprecationWarning,
                  stacklevel=2)
    return to_bytes(obj,
                    encoding='utf8',
                    errors='replace',
                    non_string=non_string)
예제 #10
0
def utf8_width_fill(msg, fill, chop=None, left=True, prefix='', suffix=''):
    '''Deprecated.

    Use :func:`~kitchen.text.display.byte_string_textual_width_fill` instead
    '''
    warnings.warn(_(
        '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)
예제 #11
0
def html_entities_unescape(string):
    '''Substitute unicode characters for HTML entities

    :arg string: Unicode string to substitute out html entities
    :raises TypeError: if something other than a unicode string is given
    :rtype: unicode string
    :returns: The plain text.  If the HTML source contains non-ASCII
      entities or character references, this is a Unicode string.
    '''
    def fixup(m):
        string = m.group(0)
        if string[:1] == "<":
            return ""  # ignore tags
        if string[:2] == "&#":
            try:
                if string[:3] == "&#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] == "&":
            entity = htmlentitydefs.entitydefs.get(string[1:-1])
            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(
            _('html_entities_unescape must have a unicode type'
              ' for its first argument'))
    return re.sub(_ENTITY_RE, fixup, string)
예제 #12
0
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 unicode strings::

        to_unicode(obj, non_string='simplerepr')

    If you need byte strings::

        to_bytes(obj, non_string='simplerepr')
    '''
    warnings.warn(_('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, non_string='simplerepr')
예제 #13
0
def utf8_text_wrap(text, width=70, initial_indent='', subsequent_indent=''):
    '''Deprecated.

    Use :func:`~kitchen.text.display.wrap` instead
    '''
    warnings.warn(_('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
예제 #14
0
def guess_encoding(byte_string, disable_chardet=False):
    '''Try to guess the encoding of a byte :class:`str`

    :arg byte_string: byte `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 reproducability whether :mod:`chardet` is installed or not.
        Default: 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 nad decoding unicode.

    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 latin1.  Since latin1 will encode to every
    byte, decoding from latin1 to :class:`unicode` will not cause
    :exc:`UnicodeErrors` even if the output is mangled.
    '''
    if not isinstance(byte_string, str):
        raise TypeError(_('byte_string must be a byte string (str)'))
    input_encoding = 'utf8'
    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 = 'latin1'

    return input_encoding
예제 #15
0
 def __init__(self, default_factory=None, *args, **kwargs):
     if (default_factory is not None
             and not hasattr(default_factory, '__call__')):
         raise TypeError(_('First argument must be callable'))
     dict.__init__(self, *args, **kwargs)
     self.default_factory = default_factory
예제 #16
0
'''
Information about this kitchen release.
'''

from kitchen import _, __version__

NAME = 'kitchen'
VERSION = __version__
DESCRIPTION = _('Kitchen contains a cornucopia of useful code')
LONG_DESCRIPTION = _('''
We've all done it.  In the process of writing a brand new application we've
discovered that we need a little bit of code that we've invented before.
Perhaps it's something to handle unicode text.  Perhaps it's something to make
a bit of python-2.5 code run on python-2.3.  Whatever it is, it ends up being
a tiny bit of code that seems too small to worry about pushing into its own
module so it sits there, a part of your current project, waiting to be cut and
pasted into your next project.  And the next.  And the next.  And since that
little bittybit of code proved so useful to you, it's highly likely that it
proved useful to someone else as well.  Useful enough that they've written it
and copy and pasted it over and over into each of their new projects.

Well, no longer!  Kitchen aims to pull these small snippets of code into a few
python modules which you can import and use within your project.  No more copy
and paste!  Now you can let someone else maintain and release these small
snippets so that you can get on with your life.
''')
AUTHOR = 'Toshio Kuratomi, Seth Vidal, others'
EMAIL = '*****@*****.**'
COPYRIGHT = '2011 Red Hat, Inc. and others'
URL = 'https://fedorahosted.org/kitchen'
DOWNLOAD_URL = 'https://fedorahosted.org/releases/k/i/kitchen'
예제 #17
0
def byte_string_to_xml(byte_string,
                       input_encoding='utf8',
                       errors='replace',
                       output_encoding='utf8',
                       attrib=False,
                       control_chars='replace'):
    '''Make sure a byte string is validly encoded for xml output

    :arg byte_string: Byte string to make sure is valid xml output
    :kwarg input_encoding: Encoding of byte_string.  Default 'utf8'
    :kwarg errors: How to handle errors encountered while decoding the
        byte_string into 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 a UnicodeDecodeError when we encounter a non-decodable
            character

    :kwarg output_encoding: Encoding for the xml file that this string will go
        into.  Default is 'utf8'.  If all the characters in 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 True, quote the string for use in an xml attribute.
        If False (default), quote for use in an xml text field.
    :kwarg control_chars: XML does not allow ASCII control characters.  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 error when we encounter a control character

    :raises XmlEncodeError: If control_chars is set to 'strict' and the string
        to be made suitable for output to xml contains control characters then
        we raise this exception.
    :raises UnicodeDecodeError: If errors is set to 'strict' and the
        byte_string contains bytes that are not decodable using input_encoding,
        this error is raised
    :rtype: byte string
    :returns: representation of the byte string in the output encoding with
        any bytes that aren't available in xml taken care of.

    Use this when you have a byte string 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 latin1 to utf8 for output::

        utf8_string = byte_string_to_xml(latin1_string, input_encoding='latin1')

    If you already have strings in the proper encoding you may still want to
    use this function to remove control characters::

        cleaned_string = byte_string_to_xml(string, input_encoding='utf8', output_encoding='utf8')

    .. seealso::

        :func:`unicode_to_xml`
            for other ideas on using this function
    '''
    if not isinstance(byte_string, str):
        raise XmlEncodeError(
            _('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)
예제 #18
0
def unicode_to_xml(string,
                   encoding='utf8',
                   attrib=False,
                   control_chars='replace'):
    '''Take a unicode string and turn it into a byte string suitable for xml

    :arg string: unicode string to encode for return
    :kwarg encoding: encoding to use for the returned byte string.  Default is
        to encode to utf8.  If all the characters in string are not encodable
        in this encoding, the unknown characters will be entered into the output
        string using xml character references.
    :kwarg attrib: If True, quote the string for use in an xml attribute.
        If False (default), quote for use in an xml text field.
    :kwarg control_chars: XML does not allow ASCII control characters.  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 error when we encounter a control character
    :raises XmlEncodeError: If control_chars is set to 'strict' and the string
        to be made suitable for output to xml contains control characters or if
        :attr:`string` is not a unicode type then we raise this exception.
    :raises ValueError: If control_chars is set to something other than
        replace, ignore, or strict.
    :rtype: byte string
    :returns: representation of the unicode string with any bytes that aren't
        available in xml taken care of.

    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 utf8::

      'String with non-ASCII characters: &lt;"á と"&gt;'

    Pretty straightforward.  Now, what if you need to encode your document in
    something other than utf8?  For instance, latin1?  Let's see::

       unicode_to_xml(u'String with non-ASCII characters: <"á と">', encoding='latin1')
       'String with non-ASCII characters: &lt;"á &#12392;"&gt;'

    Because the "と" character is not available in the latin1 charset, it is
    replaced with a "&#12392;" 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 string to unicode and replace the xmlcharrefs with the unicode
    characters.

    XML also has the quirk of not allowing ASCII control characters in its
    output.  The 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 utf7, a
    verbose encoding that encodes control values (as well as all other unicode
    values) to characters from within the ASCII printable characters.  The good
    thing about doing this is that the code is pretty simple.  You just need to
    use utf7 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 utf7 encoding will transform even characters that
    would be representable in utf8.  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 = 'utf8'
        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 utf7
            encoding = 'utf7'
            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 utf7 if there are control characters
    present.

    .. 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(
            _('unicode_to_xml must have a unicode type as'
              ' the first argument.  Use bytes_string_to_xml for byte'
              ' strings.'))
    except ValueError:
        raise ValueError(
            _('The control_chars argument to unicode_to_xml'
              ' must be one of ignore, replace, or strict'))
    except ControlCharError, e:
        raise XmlEncodeError(e.args[0])
예제 #19
0
파일: release.py 프로젝트: andelux/crawler
'''
Information about this kitchen release.
'''

from kitchen import _, __version__

NAME = 'kitchen'
VERSION = __version__
DESCRIPTION = _('Kitchen contains a cornucopia of useful code')
LONG_DESCRIPTION = _('''
We've all done it.  In the process of writing a brand new application we've
discovered that we need a little bit of code that we've invented before.
Perhaps it's something to handle unicode text.  Perhaps it's something to make
a bit of python-2.5 code run on python-2.3.  Whatever it is, it ends up being
a tiny bit of code that seems too small to worry about pushing into its own
module so it sits there, a part of your current project, waiting to be cut and
pasted into your next project.  And the next.  And the next.  And since that
little bittybit of code proved so useful to you, it's highly likely that it
proved useful to someone else as well.  Useful enough that they've written it
and copy and pasted it over and over into each of their new projects.

Well, no longer!  Kitchen aims to pull these small snippets of code into a few
python modules which you can import and use within your project.  No more copy
and paste!  Now you can let someone else maintain and release these small
snippets so that you can get on with your life.
''')
AUTHOR = 'Toshio Kuratomi, Seth Vidal, others'
EMAIL = '*****@*****.**'
COPYRIGHT = '2010 Red Hat, Inc. and others'
URL = 'https://fedorahosted.org/kitchen'
DOWNLOAD_URL = 'https://fedorahosted.org/releases/k/i/kitchen'
예제 #20
0
def to_bytes(obj, encoding='utf8', errors='replace', non_string='empty'):
    '''Convert an object into a byte string

    Usually, this should be used on a unicode string but it can take byte
    strings and unicode strings intelligently.  non_string objects are handled
    in different ways depending on the setting of the non_string parameter.

    The default values of this function are set so as to always return
    a byte string 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.

    :arg obj: Object to convert to a byte string.  This should normally be
        a unicode string.
    :kwarg encoding: Encoding to use to convert the unicode string into
        bytes.  **Warning**: if you pass a byte string into this function the
        byte string is returned unmodified.  It is not re-encoded with this
        encoding.  Defaults to utf8.
    :kwarg errors: If errors are found when encoding, perform this action.
        Defaults to 'replace' which replaces the error with a '?' character to
        show a character was unable to be encoded.  Other values are those
        that can be given to the :func:`str.encode`.  For instance
        'strict' which raises an exception and 'ignore' which simply omits the
        non-encodable characters.
    :kwargs non_string: How to treat non_string values.  Possible values are:

        :empty: Return an empty byte string (default)
        :strict: Raise a TypeError
        :passthru: Return the object unchanged
        :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: __unicode__() and
            __str__().  We first try to get a usable value from
            __str__().  If that fails we try the same with __unicode__().
        :repr: Attempt to return a byte string of the repr of the
            object

    :raises TypeError: if :attr:`non_string` is strict and a non-basestring
        object is passed in or if :attr:`non_string` is set to an unknown
        value.
    :raises UnicodeEncodeError: if :attr:`errors` is strict and all of the
        bytes of obj are unable to be encoded using :attr:`encoding`.
    :returns: byte string or the original object depending on the value of
        non_string.
    '''
    if isinstance(obj, basestring):
        if isinstance(obj, str):
            return obj
        return obj.encode(encoding, errors)
    if non_string == 'empty':
        return ''
    elif non_string == 'passthru':
        return obj
    elif non_string == '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:
                simple = ''
        if isinstance(simple, unicode):
            simple = simple.encode(encoding, 'replace')
        return simple
    elif non_string 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 non_string == 'repr':
            return obj_repr
        raise TypeError(
            _('to_bytes was given "%(obj)s" which is neither'
              ' a unicode string or a byte string (str)') % {'obj': obj_repr})

    raise TypeError(
        _('non_string value, %(param)s, is not set to a valid'
          ' action') % {'param': non_string})
예제 #21
0
def to_unicode(obj, encoding='utf8', errors='replace', non_string='empty'):
    '''Convert an object into a unicode string

    Usually, this should be used on a byte string but it can take byte strings
    and unicode strings intelligently.  non_string objects are handled in
    different ways depending on the setting of the non_string parameter.

    The default values of this function are set so as to always return
    a unicode string and never raise an error when converting from bytes to
    unicode.  However, when you do not pass validly encoded text as the byte
    string (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.

    :arg obj: Object to convert to a unicode string.  This should normally be
        a byte string
    :kwarg encoding: What encoding to try converting the byte string as.
        Defaults to utf8
    :kwarg errors: If errors are given, perform this action.  Defaults to
        'replace' which replaces the error with a character that means the bytes
        were unable to be decoded.  Other values are those that can be given to
        the unicode constructor, for instance 'strict' which raises an
        exception and 'ignore' which simply omits the non-decodable
        characters.
    :kwargs non_string: How to treat non_string values.  Possible values are:

        :empty: Return an empty string (default)
        :strict: Raise a TypeError
        :passthru: Return the object unchanged
        :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: __unicode__() and
            __str__().  We first try to get a usable value from
            __unicode__().  If that fails we try the same with __str__().
        :repr: Attempt to return a unicode string of the repr of the
            object

    :raises TypeError: if :attr:`non_string` is 'strict' and a non-basestring
        object is passed in or if :attr:`non_string` is set to an unknown value
    :raises UnicodeDecodeError: if :attr:`errors` is 'strict' and the obj is
        not decodable using the given encoding
    :returns: unicode string or the original object depending on the value of
        non_string.
    '''
    if isinstance(obj, basestring):
        if isinstance(obj, unicode):
            return obj
        return unicode(obj, encoding=encoding, errors=errors)
    if non_string == 'empty':
        return u''
    elif non_string == 'passthru':
        return obj
    elif non_string == 'simplerepr':
        try:
            simple = obj.__unicode__()
        except AttributeError:
            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 to_unicode(simple, 'utf8', 'replace')
        return simple
    elif non_string in ('repr', 'strict'):
        obj_repr = repr(obj)
        if not isinstance(obj_repr, unicode):
            unicode(obj_repr, encoding=encoding, errors=errors)
        if non_string == 'repr':
            return obj_repr
        raise TypeError(
            _('to_unicode was given "%(obj)s" which is neither'
              ' a byte string (str) or a unicode string') % {'obj': obj_repr})

    raise TypeError(
        _('non_string value, %(param)s, is not set to a valid'
          ' action') % {'param': non_string})