示例#1
0
def _validate_response_content(
        response: requests.Response,
        data_schema: Optional[Schema] = None) -> Optional[Any]:
    if data_schema is None:
        return None

    try:
        try:
            mimetype: Optional[MimeTypeTolerant] = MimeType.from_name(
                response.headers.get("Content-Type"))
        except ValueError:
            mimetype = None

        loaded, _ = decode_content(
            response.content,
            mimetype=mimetype,
            data_schema=data_schema,
            allow_sniff=True,
        )
        return loaded

    except (json.JSONDecodeError, InvalidBSON, InvalidDocument,
            UnicodeDecodeError):
        raise ContentDecodeError("Could not load response data.")

    except ValidationError:
        raise DataValidationError("Error validating returned data")
示例#2
0
    def test_schema_round_trip(self, mimetype):

        data = DataToTest()
        schema = SchemaToTest()
        headers = dict()

        encoded = encode_content(
            data, mimetype=mimetype, headers=headers, data_schema=schema
        )
        print(encoded.decode())

        assert isinstance(encoded, bytes)
        header_content_type = headers["Content-Type"]
        if mimetype is None:
            assert header_content_type == MimeType.JSON.value
        else:
            assert header_content_type == MimeType.from_name(mimetype).value

        loaded, decoded = decode_content(
            encoded, mimetype=mimetype, data_schema=schema, allow_sniff=True
        )

        assert isinstance(loaded, DataToTest)
        assert loaded == data

        assert isinstance(decoded, Mapping)
示例#3
0
 def mimetype(self) -> Union[str, MimeType]:
     """Mimetype pulled from ``'Content-Type'`` request header."""
     mimetype = super().mimetype
     try:
         return MimeType.from_name(mimetype)
     except ValueError:
         return mimetype
示例#4
0
def register_mimetype(mimetype: MimeTypeTolerant, encoder: EncoderType,
                      decoder: DecoderType) -> None:
    try:
        mimetype = MimeType.from_name(mimetype)
    except ValueError:
        pass

    SpanClient._ENCODERS[mimetype] = encoder
    SpanClient._DECODERS[mimetype] = decoder
示例#5
0
    def test_data_round_trip(self, mimetype):
        data = {"key": 10}
        headers = dict()

        encoded = encode_content(data, mimetype=mimetype, headers=headers)
        print(str(encoded))

        assert isinstance(encoded, bytes)
        assert headers["Content-Type"] == MimeType.from_name(mimetype).value

        loaded, decoded = decode_content(encoded, mimetype=mimetype)

        assert dict(decoded) == dict(loaded) == data
示例#6
0
    def register_mimetype(self, mimetype: MimeTypeTolerant,
                          encoder: EncoderType, decoder: DecoderType) -> None:
        """
        Registers encoder and decoder function for a given mimetype.

        :param mimetype: to register for ex: ``'text/csv'``.
        :param encoder: Encodes mimetype data to binary.
        :param decoder: Decodes mimetype data to binary.
        :return:
        """
        try:
            mimetype = MimeType.from_name(mimetype)
        except ValueError:
            pass

        self._encoders[mimetype] = encoder
        self._decoders[mimetype] = decoder
    def mimetype(self) -> MimeTypeTolerant:
        if self._mimetype is NOT_LOADED:

            # Check the builtin content type first.
            mimetype: MimeTypeTolerant = self.message.content_type
            if not mimetype:
                # if that is none, check the custom header.
                mimetype = self.headers.get("Content-Type")

            if mimetype:
                try:
                    mimetype = MimeType.from_name(mimetype)
                except ValueError:
                    pass
            else:
                mimetype = None

            self._mimetype = mimetype

        return self._mimetype
 def test_mimetype_parsing(self, name: str):
     assert MimeType.from_name(name) is MimeType.JSON