PageRenderTime 23ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/django-1.5/django/utils/encoding.py

https://github.com/theosp/google_appengine
Python | 244 lines | 187 code | 11 blank | 46 comment | 9 complexity | 4bb8f50e0f958bcb37b0ee86197ad9a9 MD5 | raw file
  1. from __future__ import unicode_literals
  2. import codecs
  3. import datetime
  4. from decimal import Decimal
  5. import locale
  6. try:
  7. from urllib.parse import quote
  8. except ImportError: # Python 2
  9. from urllib import quote
  10. import warnings
  11. from django.utils.functional import Promise
  12. from django.utils import six
  13. class DjangoUnicodeDecodeError(UnicodeDecodeError):
  14. def __init__(self, obj, *args):
  15. self.obj = obj
  16. UnicodeDecodeError.__init__(self, *args)
  17. def __str__(self):
  18. original = UnicodeDecodeError.__str__(self)
  19. return '%s. You passed in %r (%s)' % (original, self.obj,
  20. type(self.obj))
  21. class StrAndUnicode(object):
  22. """
  23. A class that derives __str__ from __unicode__.
  24. On Python 2, __str__ returns the output of __unicode__ encoded as a UTF-8
  25. bytestring. On Python 3, __str__ returns the output of __unicode__.
  26. Useful as a mix-in. If you support Python 2 and 3 with a single code base,
  27. you can inherit this mix-in and just define __unicode__.
  28. """
  29. def __init__(self, *args, **kwargs):
  30. warnings.warn("StrAndUnicode is deprecated. Define a __str__ method "
  31. "and apply the @python_2_unicode_compatible decorator "
  32. "instead.", PendingDeprecationWarning, stacklevel=2)
  33. super(StrAndUnicode, self).__init__(*args, **kwargs)
  34. if six.PY3:
  35. def __str__(self):
  36. return self.__unicode__()
  37. else:
  38. def __str__(self):
  39. return self.__unicode__().encode('utf-8')
  40. def python_2_unicode_compatible(klass):
  41. """
  42. A decorator that defines __unicode__ and __str__ methods under Python 2.
  43. Under Python 3 it does nothing.
  44. To support Python 2 and 3 with a single code base, define a __str__ method
  45. returning text and apply this decorator to the class.
  46. """
  47. if not six.PY3:
  48. klass.__unicode__ = klass.__str__
  49. klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
  50. return klass
  51. def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
  52. """
  53. Returns a text object representing 's' -- unicode on Python 2 and str on
  54. Python 3. Treats bytestrings using the 'encoding' codec.
  55. If strings_only is True, don't convert (some) non-string-like objects.
  56. """
  57. if isinstance(s, Promise):
  58. # The input is the result of a gettext_lazy() call.
  59. return s
  60. return force_text(s, encoding, strings_only, errors)
  61. def is_protected_type(obj):
  62. """Determine if the object instance is of a protected type.
  63. Objects of protected types are preserved as-is when passed to
  64. force_text(strings_only=True).
  65. """
  66. return isinstance(obj, six.integer_types + (type(None), float, Decimal,
  67. datetime.datetime, datetime.date, datetime.time))
  68. def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
  69. """
  70. Similar to smart_text, except that lazy instances are resolved to
  71. strings, rather than kept as lazy objects.
  72. If strings_only is True, don't convert (some) non-string-like objects.
  73. """
  74. # Handle the common case first, saves 30-40% when s is an instance of
  75. # six.text_type. This function gets called often in that setting.
  76. if isinstance(s, six.text_type):
  77. return s
  78. if strings_only and is_protected_type(s):
  79. return s
  80. try:
  81. if not isinstance(s, six.string_types):
  82. if hasattr(s, '__unicode__'):
  83. s = s.__unicode__()
  84. else:
  85. if six.PY3:
  86. if isinstance(s, bytes):
  87. s = six.text_type(s, encoding, errors)
  88. else:
  89. s = six.text_type(s)
  90. else:
  91. s = six.text_type(bytes(s), encoding, errors)
  92. else:
  93. # Note: We use .decode() here, instead of six.text_type(s, encoding,
  94. # errors), so that if s is a SafeBytes, it ends up being a
  95. # SafeText at the end.
  96. s = s.decode(encoding, errors)
  97. except UnicodeDecodeError as e:
  98. if not isinstance(s, Exception):
  99. raise DjangoUnicodeDecodeError(s, *e.args)
  100. else:
  101. # If we get to here, the caller has passed in an Exception
  102. # subclass populated with non-ASCII bytestring data without a
  103. # working unicode method. Try to handle this without raising a
  104. # further exception by individually forcing the exception args
  105. # to unicode.
  106. s = ' '.join([force_text(arg, encoding, strings_only,
  107. errors) for arg in s])
  108. return s
  109. def smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
  110. """
  111. Returns a bytestring version of 's', encoded as specified in 'encoding'.
  112. If strings_only is True, don't convert (some) non-string-like objects.
  113. """
  114. if isinstance(s, Promise):
  115. # The input is the result of a gettext_lazy() call.
  116. return s
  117. return force_bytes(s, encoding, strings_only, errors)
  118. def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
  119. """
  120. Similar to smart_bytes, except that lazy instances are resolved to
  121. strings, rather than kept as lazy objects.
  122. If strings_only is True, don't convert (some) non-string-like objects.
  123. """
  124. if isinstance(s, bytes):
  125. if encoding == 'utf-8':
  126. return s
  127. else:
  128. return s.decode('utf-8', errors).encode(encoding, errors)
  129. if strings_only and (s is None or isinstance(s, int)):
  130. return s
  131. if isinstance(s, Promise):
  132. return six.text_type(s).encode(encoding, errors)
  133. if not isinstance(s, six.string_types):
  134. try:
  135. if six.PY3:
  136. return six.text_type(s).encode(encoding)
  137. else:
  138. return bytes(s)
  139. except UnicodeEncodeError:
  140. if isinstance(s, Exception):
  141. # An Exception subclass containing non-ASCII data that doesn't
  142. # know how to print itself properly. We shouldn't raise a
  143. # further exception.
  144. return b' '.join([force_bytes(arg, encoding, strings_only,
  145. errors) for arg in s])
  146. return six.text_type(s).encode(encoding, errors)
  147. else:
  148. return s.encode(encoding, errors)
  149. if six.PY3:
  150. smart_str = smart_text
  151. force_str = force_text
  152. else:
  153. smart_str = smart_bytes
  154. force_str = force_bytes
  155. # backwards compatibility for Python 2
  156. smart_unicode = smart_text
  157. force_unicode = force_text
  158. smart_str.__doc__ = """\
  159. Apply smart_text in Python 3 and smart_bytes in Python 2.
  160. This is suitable for writing to sys.stdout (for instance).
  161. """
  162. force_str.__doc__ = """\
  163. Apply force_text in Python 3 and force_bytes in Python 2.
  164. """
  165. def iri_to_uri(iri):
  166. """
  167. Convert an Internationalized Resource Identifier (IRI) portion to a URI
  168. portion that is suitable for inclusion in a URL.
  169. This is the algorithm from section 3.1 of RFC 3987. However, since we are
  170. assuming input is either UTF-8 or unicode already, we can simplify things a
  171. little from the full method.
  172. Returns an ASCII string containing the encoded result.
  173. """
  174. # The list of safe characters here is constructed from the "reserved" and
  175. # "unreserved" characters specified in sections 2.2 and 2.3 of RFC 3986:
  176. # reserved = gen-delims / sub-delims
  177. # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
  178. # sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  179. # / "*" / "+" / "," / ";" / "="
  180. # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  181. # Of the unreserved characters, urllib.quote already considers all but
  182. # the ~ safe.
  183. # The % character is also added to the list of safe characters here, as the
  184. # end of section 3.1 of RFC 3987 specifically mentions that % must not be
  185. # converted.
  186. if iri is None:
  187. return iri
  188. return quote(force_bytes(iri), safe=b"/#%[]=:;$&()+,!?*@'~")
  189. def filepath_to_uri(path):
  190. """Convert a file system path to a URI portion that is suitable for
  191. inclusion in a URL.
  192. We are assuming input is either UTF-8 or unicode already.
  193. This method will encode certain chars that would normally be recognized as
  194. special chars for URIs. Note that this method does not encode the '
  195. character, as it is a valid character within URIs. See
  196. encodeURIComponent() JavaScript function for more details.
  197. Returns an ASCII string containing the encoded result.
  198. """
  199. if path is None:
  200. return path
  201. # I know about `os.sep` and `os.altsep` but I want to leave
  202. # some flexibility for hardcoding separators.
  203. return quote(force_bytes(path).replace(b"\\", b"/"), safe=b"/~!*()'")
  204. # The encoding of the default system locale but falls back to the
  205. # given fallback encoding if the encoding is unsupported by python or could
  206. # not be determined. See tickets #10335 and #5846
  207. try:
  208. DEFAULT_LOCALE_ENCODING = locale.getdefaultlocale()[1] or 'ascii'
  209. codecs.lookup(DEFAULT_LOCALE_ENCODING)
  210. except:
  211. DEFAULT_LOCALE_ENCODING = 'ascii'