diff options
Diffstat (limited to 'boto/utils.py')
-rw-r--r-- | boto/utils.py | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/boto/utils.py b/boto/utils.py index 83b429b9..173594e2 100644 --- a/boto/utils.py +++ b/boto/utils.py @@ -1084,3 +1084,28 @@ def parse_host(hostname): else: return hostname.split(':', 1)[0] + +def get_utf8able_str(s, errors='strict'): + """Returns a UTF8-encodable string in PY3, UTF8 bytes in PY2. + + This method is similar to six's `ensure_str()`, except it also + makes sure that any bytes passed in can be decoded using the + utf-8 codec (and raises a UnicodeDecodeError if not). + """ + if six.PY2: + # We want to return utf-8 encoded bytes. + if isinstance(s, six.text_type): + return s.encode('utf-8', errors) + if isinstance(s, six.binary_type): + # Verify the bytes can be represented in utf-8 + s.decode('utf-8') + return s + else: + # We want to return a unicode/str object. + if isinstance(s, six.text_type): + return s + if isinstance(s, six.binary_type): + s = s.decode('utf-8') + return s + raise TypeError('not expecting type "%s"' % type(s)) + |