1
0
mirror of https://github.com/django/django.git synced 2025-10-25 22:56:12 +00:00

[py3] Replaced unicode/str by six.text_type/bytes.

This commit is contained in:
Aymeric Augustin
2012-07-20 14:48:51 +02:00
parent 3cb2457f46
commit bdca5ea345
96 changed files with 376 additions and 294 deletions

View File

@@ -25,8 +25,12 @@ class StrAndUnicode(object):
Useful as a mix-in.
"""
def __str__(self):
return self.__unicode__().encode('utf-8')
if six.PY3:
def __str__(self):
return self.__unicode__()
else:
def __str__(self):
return self.__unicode__().encode('utf-8')
def smart_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
@@ -59,17 +63,23 @@ def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
# Handle the common case first, saves 30-40% in performance when s
# is an instance of unicode. This function gets called often in that
# setting.
if isinstance(s, unicode):
if isinstance(s, six.text_type):
return s
if strings_only and is_protected_type(s):
return s
try:
if not isinstance(s, six.string_types,):
if not isinstance(s, six.string_types):
if hasattr(s, '__unicode__'):
s = unicode(s)
s = s.__unicode__()
else:
try:
s = unicode(str(s), encoding, errors)
if six.PY3:
if isinstance(s, bytes):
s = six.text_type(s, encoding, errors)
else:
s = six.text_type(s)
else:
s = six.text_type(bytes(s), encoding, errors)
except UnicodeEncodeError:
if not isinstance(s, Exception):
raise
@@ -81,8 +91,8 @@ def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
# output should be.
s = ' '.join([force_unicode(arg, encoding, strings_only,
errors) for arg in s])
elif not isinstance(s, unicode):
# Note: We use .decode() here, instead of unicode(s, encoding,
elif not isinstance(s, six.text_type):
# Note: We use .decode() here, instead of six.text_type(s, encoding,
# errors), so that if s is a SafeString, it ends up being a
# SafeUnicode at the end.
s = s.decode(encoding, errors)
@@ -108,10 +118,13 @@ def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
if strings_only and (s is None or isinstance(s, int)):
return s
if isinstance(s, Promise):
return unicode(s).encode(encoding, errors)
return six.text_type(s).encode(encoding, errors)
elif not isinstance(s, six.string_types):
try:
return str(s)
if six.PY3:
return six.text_type(s).encode(encoding)
else:
return bytes(s)
except UnicodeEncodeError:
if isinstance(s, Exception):
# An Exception subclass containing non-ASCII data that doesn't
@@ -119,8 +132,8 @@ def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
# further exception.
return ' '.join([smart_str(arg, encoding, strings_only,
errors) for arg in s])
return unicode(s).encode(encoding, errors)
elif isinstance(s, unicode):
return six.text_type(s).encode(encoding, errors)
elif isinstance(s, six.text_type):
return s.encode(encoding, errors)
elif s and encoding != 'utf-8':
return s.decode('utf-8', errors).encode(encoding, errors)