Exemple #1
0
def html_escape(s):
    """HTML-escape a string or object

    This converts any non-string objects passed into it to strings
    (actually, using ``unicode()``).  All values returned are
    non-unicode strings (using ``&#num;`` entities for all non-ASCII
    characters).

    None is treated specially, and returns the empty string.
    """
    if s is None:
        return ''
    __html__ = getattr(s, '__html__', None)
    if __html__ is not None and callable(__html__):
        return s.__html__()
    if not isinstance(s, string_types):
        __unicode__ = getattr(s, '__unicode__', None)
        if __unicode__ is not None and callable(__unicode__):
            s = s.__unicode__()
        else:
            s = str(s)
    s = escape(s, True)
    if isinstance(s, text_type):
        s = s.encode('ascii', 'xmlcharrefreplace')
    return text_(s)
Exemple #2
0
def html_escape(s):
    """HTML-escape a string or object

    This converts any non-string objects passed into it to strings
    (actually, using ``unicode()``).  All values returned are
    non-unicode strings (using ``&#num;`` entities for all non-ASCII
    characters).

    None is treated specially, and returns the empty string.
    """
    if s is None:
        return ''
    __html__ = getattr(s, '__html__', None)
    if __html__ is not None and callable(__html__):
        return s.__html__()
    if not isinstance(s, string_types):
        __unicode__ = getattr(s, '__unicode__', None)
        if __unicode__ is not None and callable(__unicode__):
            s = s.__unicode__()
        else:
            s = str(s)
    s = escape(s, True)
    if isinstance(s, text_type):
        s = s.encode('ascii', 'xmlcharrefreplace')
    return text_(s)