图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.7 KiB

  1. from ..exceptions import DataError
  2. class Encoder:
  3. "Encode strings to bytes-like and decode bytes-like to strings"
  4. __slots__ = "encoding", "encoding_errors", "decode_responses"
  5. def __init__(self, encoding, encoding_errors, decode_responses):
  6. self.encoding = encoding
  7. self.encoding_errors = encoding_errors
  8. self.decode_responses = decode_responses
  9. def encode(self, value):
  10. "Return a bytestring or bytes-like representation of the value"
  11. if isinstance(value, (bytes, memoryview)):
  12. return value
  13. elif isinstance(value, bool):
  14. # special case bool since it is a subclass of int
  15. raise DataError(
  16. "Invalid input of type: 'bool'. Convert to a "
  17. "bytes, string, int or float first."
  18. )
  19. elif isinstance(value, (int, float)):
  20. value = repr(value).encode()
  21. elif not isinstance(value, str):
  22. # a value we don't know how to deal with. throw an error
  23. typename = type(value).__name__
  24. raise DataError(
  25. f"Invalid input of type: '{typename}'. "
  26. f"Convert to a bytes, string, int or float first."
  27. )
  28. if isinstance(value, str):
  29. value = value.encode(self.encoding, self.encoding_errors)
  30. return value
  31. def decode(self, value, force=False):
  32. "Return a unicode string from the bytes-like representation"
  33. if self.decode_responses or force:
  34. if isinstance(value, memoryview):
  35. value = value.tobytes()
  36. if isinstance(value, bytes):
  37. value = value.decode(self.encoding, self.encoding_errors)
  38. return value