def deserialize_from_text()

in azext_iot/sdk/deviceupdate/controlplane/_serialization.py [0:0]


    def deserialize_from_text(cls, data, content_type=None):
        # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any
        """Decode data according to content-type.

        Accept a stream of data as well, but will be load at once in memory for now.

        If no content-type, will return the string version (not bytes, not stream)

        :param data: Input, could be bytes or stream (will be decoded with UTF8) or text
        :type data: str or bytes or IO
        :param str content_type: The content type.
        """
        if hasattr(data, 'read'):
            # Assume a stream
            data = cast(IO, data).read()

        if isinstance(data, bytes):
            data_as_str = data.decode(encoding='utf-8-sig')
        else:
            # Explain to mypy the correct type.
            data_as_str = cast(str, data)

            # Remove Byte Order Mark if present in string
            data_as_str = data_as_str.lstrip(_BOM)

        if content_type is None:
            return data

        if cls.JSON_REGEXP.match(content_type):
            try:
                return json.loads(data_as_str)
            except ValueError as err:
                raise DeserializationError("JSON is invalid: {}".format(err), err)
        elif "xml" in (content_type or []):
            try:

                try:
                    if isinstance(data, unicode):  # type: ignore
                        # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string
                        data_as_str = data_as_str.encode(encoding="utf-8")  # type: ignore
                except NameError:
                    pass

                return ET.fromstring(data_as_str)
            except ET.ParseError:
                # It might be because the server has an issue, and returned JSON with
                # content-type XML....
                # So let's try a JSON load, and if it's still broken
                # let's flow the initial exception
                def _json_attemp(data):
                    try:
                        return True, json.loads(data)
                    except ValueError:
                        return False, None # Don't care about this one
                success, json_result = _json_attemp(data)
                if success:
                    return json_result
                # If i'm here, it's not JSON, it's not XML, let's scream
                # and raise the last context in this block (the XML exception)
                # The function hack is because Py2.7 messes up with exception
                # context otherwise.
                _LOGGER.critical("Wasn't XML not JSON, failing")
                raise_with_traceback(DeserializationError, "XML is invalid")
        raise DeserializationError("Cannot deserialize content-type: {}".format(content_type))