Add support for gzip, deflate, and brotli decoding
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parent 9d59a5a · Browse files · 5 files·+213 added−34 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+213 added−34 removed
- tests:+79 added−0 removed
- other:+134 added−34 removed
Provenance
- Commit
39b57c9- Tree
ee4b292- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
9d59a5a
5 files changed+213 added−34 removed
added:httpcore/compat.py+4 added
1+try:2+ import brotli3+except ImportError:4+ brotli = Nonemodified:httpcore/datastructures.py+18 added-3 removed
1 import typing2 from urllib.parse import urlsplit3 4-from .decoders import IdentityDecoder4+from .decoders import SUPPORTED_DECODERS, Decoder, IdentityDecoder, MultiDecoder5 from .exceptions import ResponseClosed, StreamConsumed6 7 8 class URL:85 unmodified lines94 self.headers = list(headers)95 self.on_close = on_close96 self.is_closed = False97 self.is_streamed = False98+99+ decoders = [] # type: typing.List[Decoder]100+ for header, value in self.headers:101+ if header.strip().lower() == b"content-encoding":102+ for part in value.split(b","):103+ part = part.strip().lower()104+ decoder_cls = SUPPORTED_DECODERS[part]105+ decoders.append(decoder_cls())106+107+ if len(decoders) == 0:98- self.decoder = IdentityDecoder()108+ self.decoder = IdentityDecoder() # type: Decoder109+ elif len(decoders) == 1:110+ self.decoder = decoders[0]111+ else:112+ self.decoder = MultiDecoder(decoders)113+114 if isinstance(body, bytes):115 self.is_closed = True101- self.body = body116+ self.body = self.decoder.decode(body) + self.decoder.flush()117 else:118 self.body_aiter = body119 120 async def read(self) -> bytes:40 unmodified linesmodified:httpcore/decoders.py+108 added-31 removed
1 """2 Handlers for Content-Encoding.3+4+See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding5 """6+import typing7+import zlib8 9+from .compat import brotli10 6-class IdentityDecoder:7- def decode(self, chunk: bytes) -> bytes:8- return chunk11 12+class Decoder:13+ def decode(self, data: bytes) -> bytes:14+ raise NotImplementedError() # pragma: nocover15+16 def flush(self) -> bytes:17+ raise NotImplementedError() # pragma: nocover18+19+20+class IdentityDecoder(Decoder):21+ def decode(self, data: bytes) -> bytes:22+ return data23+24+ def flush(self) -> bytes:25 return b""26 27 14-# class DeflateDecoder:15-# pass16-#17-#18-# class GZipDecoder:19-# pass20-#21-#22-# class BrotliDecoder:23-# pass24-#25-#26-# class MultiDecoder:27-# def __init__(self, children):28-# self.children = children29-#30-# def decode(self, chunk: bytes) -> bytes:31-# data = chunk32-# for child in children:33-# data = child.decode(data)34-# return data35-#36-# def flush(self) -> bytes:37-# data = b''38-# for child in children:39-# data = child.decode(data)40-# data = child.flush()41-# return data28+class DeflateDecoder(Decoder):29+ """30+ Handle 'deflate' decoding.31+32+ See: https://stackoverflow.com/questions/183869933+ """34+35+ def __init__(self) -> None:36+ self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)37+38+ def decode(self, data: bytes) -> bytes:39+ return self.decompressor.decompress(data)40+41+ def flush(self) -> bytes:42+ return self.decompressor.flush()43+44+45+class GZipDecoder(Decoder):46+ """47+ Handle 'gzip' decoding.48+49+ See: https://stackoverflow.com/questions/183869950+ """51+52+ def __init__(self) -> None:53+ self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)54+55+ def decode(self, data: bytes) -> bytes:56+ return self.decompressor.decompress(data)57+58+ def flush(self) -> bytes:59+ return self.decompressor.flush()60+61+62+class BrotliDecoder(Decoder):63+ """64+ Handle 'brotli' decoding.65+66+ Requires `pip install brotlipy`.67+ See: https://brotlipy.readthedocs.io/68+ """69+70+ def __init__(self) -> None:71+ assert (72+ brotli is not None73+ ), "The 'brotlipy' library must be installed to use 'BrotliDecoder'"74+ self.decompressor = brotli.Decompressor()75+76+ def decode(self, data: bytes) -> bytes:77+ return self.decompressor.decompress(data)78+79+ def flush(self) -> bytes:80+ self.decompressor.finish()81+ return b""82+83+84+class MultiDecoder(Decoder):85+ """86+ Handle the case where mutliple encodings have been applied.87+ """88+89+ def __init__(self, children: typing.Sequence[Decoder]) -> None:90+ """91+ children should be a sequence of decoders in the order in which92+ each was applied.93+ """94+ # Note that we reverse the order for decoding.95+ self.children = list(reversed(children))96+97+ def decode(self, data: bytes) -> bytes:98+ for child in self.children:99+ data = child.decode(data)100+ return data101+102+ def flush(self) -> bytes:103+ data = b""104+ for child in self.children:105+ data = child.decode(data) + child.flush()106+ return data107+108+109+SUPPORTED_DECODERS = {110+ b"gzip": GZipDecoder,111+ b"deflate": DeflateDecoder,112+ b"identity": IdentityDecoder,113+ b"br": BrotliDecoder,114+}115+116+117+if brotli is None:118+ SUPPORTED_DECODERS.pop(b"br") # pragma: nocoveradded:tests/test_decoding.py+79 added
1+import zlib2+3+import brotli4+import pytest5+6+import httpcore7+8+9+def test_deflate():10+ body = b"test 123"11+ compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)12+ compressed_body = compressor.compress(body) + compressor.flush()13+14+ headers = [(b"Content-Encoding", b"deflate")]15+ response = httpcore.Response(200, headers=headers, body=compressed_body)16+ assert response.body == body17+18+19+def test_gzip():20+ body = b"test 123"21+ compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)22+ compressed_body = compressor.compress(body) + compressor.flush()23+24+ headers = [(b"Content-Encoding", b"gzip")]25+ response = httpcore.Response(200, headers=headers, body=compressed_body)26+ assert response.body == body27+28+29+def test_brotli():30+ body = b"test 123"31+ compressed_body = brotli.compress(body)32+33+ headers = [(b"Content-Encoding", b"br")]34+ response = httpcore.Response(200, headers=headers, body=compressed_body)35+ assert response.body == body36+37+38+def test_multi():39+ body = b"test 123"40+41+ deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)42+ compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()43+44+ gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)45+ compressed_body = (46+ gzip_compressor.compress(compressed_body) + gzip_compressor.flush()47+ )48+49+ headers = [(b"Content-Encoding", b"deflate, gzip")]50+ response = httpcore.Response(200, headers=headers, body=compressed_body)51+ assert response.body == body52+53+54+def test_multi_with_identity():55+ body = b"test 123"56+ compressed_body = brotli.compress(body)57+58+ headers = [(b"Content-Encoding", b"br, identity")]59+ response = httpcore.Response(200, headers=headers, body=compressed_body)60+ assert response.body == body61+62+ headers = [(b"Content-Encoding", b"identity, br")]63+ response = httpcore.Response(200, headers=headers, body=compressed_body)64+ assert response.body == body65+66+67+@pytest.mark.asyncio68+async def test_streaming():69+ body = b"test 123"70+ compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)71+72+ async def compress(body):73+ yield compressor.compress(body)74+ yield compressor.flush()75+76+ headers = [(b"Content-Encoding", b"gzip")]77+ response = httpcore.Response(200, headers=headers, body=compress(body))78+ assert not hasattr(response, "body")79+ assert await response.read() == bodymodified:requirements.txt+4 added
1 certifi2 h113 4+# Optional5+brotlipy6+7+8 # Testing9 autoflake10 black11 codecov6 unmodified lines