Skip to content
Myr

decoders.py

This file

Path

httpcore/decoders.py

149 lines · 3.7 KiB · Python

Last changed by

Merge pull request #62 from yeraydiazdiaz/exclude-decoders-flush-from-coverageTom Christiebefore adoption51562dc

History of this file

Take it

1"""2Handlers for Content-Encoding.34See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding5"""6import typing7import zlib89import httpcore.exceptions1011try:12    import brotli13except ImportError:  # pragma: nocover14    brotli = None151617class Decoder:18    def decode(self, data: bytes) -> bytes:19        raise NotImplementedError()  # pragma: nocover2021    def flush(self) -> bytes:22        raise NotImplementedError()  # pragma: nocover232425class IdentityDecoder(Decoder):26    """27    Handle unencoded data.28    """2930    def decode(self, data: bytes) -> bytes:31        return data3233    def flush(self) -> bytes:34        return b""353637class DeflateDecoder(Decoder):38    """39    Handle 'deflate' decoding.4041    See: https://stackoverflow.com/questions/183869942    """4344    def __init__(self) -> None:45        self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)4647    def decode(self, data: bytes) -> bytes:48        try:49            return self.decompressor.decompress(data)50        except zlib.error as exc:51            raise httpcore.exceptions.DecodingError from exc5253    def flush(self) -> bytes:54        try:55            return self.decompressor.flush()56        except zlib.error as exc:  # pragma: nocover57            raise httpcore.exceptions.DecodingError from exc585960class GZipDecoder(Decoder):61    """62    Handle 'gzip' decoding.6364    See: https://stackoverflow.com/questions/183869965    """6667    def __init__(self) -> None:68        self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)6970    def decode(self, data: bytes) -> bytes:71        try:72            return self.decompressor.decompress(data)73        except zlib.error as exc:74            raise httpcore.exceptions.DecodingError from exc7576    def flush(self) -> bytes:77        try:78            return self.decompressor.flush()79        except zlib.error as exc:  # pragma: nocover80            raise httpcore.exceptions.DecodingError from exc818283class BrotliDecoder(Decoder):84    """85    Handle 'brotli' decoding.8687    Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/88    """8990    def __init__(self) -> None:91        assert (92            brotli is not None93        ), "The 'brotlipy' library must be installed to use 'BrotliDecoder'"94        self.decompressor = brotli.Decompressor()9596    def decode(self, data: bytes) -> bytes:97        try:98            return self.decompressor.decompress(data)99        except brotli.Error as exc:100            raise httpcore.exceptions.DecodingError from exc101102    def flush(self) -> bytes:103        try:104            self.decompressor.finish()105            return b""106        except brotli.Error as exc:  # pragma: nocover107            raise httpcore.exceptions.DecodingError from exc108109110class MultiDecoder(Decoder):111    """112    Handle the case where multiple encodings have been applied.113    """114115    def __init__(self, children: typing.Sequence[Decoder]) -> None:116        """117        'children' should be a sequence of decoders in the order in which118        each was applied.119        """120        # Note that we reverse the order for decoding.121        self.children = list(reversed(children))122123    def decode(self, data: bytes) -> bytes:124        for child in self.children:125            data = child.decode(data)126        return data127128    def flush(self) -> bytes:129        data = b""130        for child in self.children:131            data = child.decode(data) + child.flush()132        return data133134135SUPPORTED_DECODERS = {136    "identity": IdentityDecoder,137    "deflate": DeflateDecoder,138    "gzip": GZipDecoder,139    "br": BrotliDecoder,140}141142143if brotli is None:144    SUPPORTED_DECODERS.pop("br")  # pragma: nocover145146147ACCEPT_ENCODING = ", ".join(148    [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]149)