compat.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import sys
  2. from aliyunsdkcore.vendored import six
  3. if six.PY2:
  4. from base64 import encodestring as b64_encode_bytes
  5. from base64 import decodestring as b64_decode_bytes
  6. def ensure_bytes(s, encoding='utf-8', errors='strict'):
  7. if isinstance(s, unicode):
  8. return s.encode(encoding, errors)
  9. if isinstance(s, str):
  10. return s
  11. raise ValueError("Expected str or unicode, received %s." % type(s))
  12. def ensure_string(s, encoding='utf-8', errors='strict'):
  13. if isinstance(s, unicode):
  14. return s.encode(encoding, errors)
  15. if isinstance(s, str):
  16. return s
  17. raise ValueError("Expected str or unicode, received %s." % type(s))
  18. else:
  19. from base64 import encodebytes as b64_encode_bytes
  20. from base64 import decodebytes as b64_decode_bytes
  21. def ensure_bytes(s, encoding='utf-8', errors='strict'):
  22. if isinstance(s, str):
  23. return bytes(s, encoding=encoding)
  24. if isinstance(s, bytes):
  25. return s
  26. if isinstance(s, bytearray):
  27. return bytes(s)
  28. raise ValueError(
  29. "Expected str or bytes or bytearray, received %s." %
  30. type(s))
  31. def ensure_string(s, encoding='utf-8', errors='strict'):
  32. if isinstance(s, str):
  33. return s
  34. if isinstance(s, (bytes, bytearray)):
  35. return str(s, encoding='utf-8')
  36. raise ValueError(
  37. "Expected str or bytes or bytearray, received %s." %
  38. type(s))