Skip to content
Myr

Merge pull request #2 from encode/decompression

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Add support for gzip, deflate, and brotli decoding

authored by Tom Christie · committed by GitHub · parents f0eb1c0, 39b57c9 · 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

5 files+213 added−34 removed

added:httpcore/compat.py+4 added
1try:2 import brotli3except ImportError:4 brotli = None
modified:httpcore/datastructures.py+18 added-3 removed
1import typing2from urllib.parse import urlsplit34from .decoders import IdentityDecoder4from .decoders import SUPPORTED_DECODERS, Decoder, IdentityDecoder, MultiDecoder5from .exceptions import ResponseClosed, StreamConsumed678class URL:
85 unmodified lines
94 self.headers = list(headers)95 self.on_close = on_close96 self.is_closed = False97 self.is_streamed = False9899 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())106107 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)113114 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 = body119120 async def read(self) -> bytes:
40 unmodified lines
modified:httpcore/decoders.py+108 added-31 removed
1"""2Handlers for Content-Encoding.34See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding5"""6import typing7import zlib89from .compat import brotli106class IdentityDecoder:7 def decode(self, chunk: bytes) -> bytes:8 return chunk1112class Decoder:13 def decode(self, data: bytes) -> bytes:14 raise NotImplementedError() # pragma: nocover1516 def flush(self) -> bytes:17 raise NotImplementedError() # pragma: nocover181920class IdentityDecoder(Decoder):21 def decode(self, data: bytes) -> bytes:22 return data2324 def flush(self) -> bytes:25 return b""262714# 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 data28class DeflateDecoder(Decoder):29 """30 Handle 'deflate' decoding.3132 See: https://stackoverflow.com/questions/183869933 """3435 def __init__(self) -> None:36 self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)3738 def decode(self, data: bytes) -> bytes:39 return self.decompressor.decompress(data)4041 def flush(self) -> bytes:42 return self.decompressor.flush()434445class GZipDecoder(Decoder):46 """47 Handle 'gzip' decoding.4849 See: https://stackoverflow.com/questions/183869950 """5152 def __init__(self) -> None:53 self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)5455 def decode(self, data: bytes) -> bytes:56 return self.decompressor.decompress(data)5758 def flush(self) -> bytes:59 return self.decompressor.flush()606162class BrotliDecoder(Decoder):63 """64 Handle 'brotli' decoding.6566 Requires `pip install brotlipy`.67 See: https://brotlipy.readthedocs.io/68 """6970 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()7576 def decode(self, data: bytes) -> bytes:77 return self.decompressor.decompress(data)7879 def flush(self) -> bytes:80 self.decompressor.finish()81 return b""828384class MultiDecoder(Decoder):85 """86 Handle the case where mutliple encodings have been applied.87 """8889 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))9697 def decode(self, data: bytes) -> bytes:98 for child in self.children:99 data = child.decode(data)100 return data101102 def flush(self) -> bytes:103 data = b""104 for child in self.children:105 data = child.decode(data) + child.flush()106 return data107108109SUPPORTED_DECODERS = {110 b"gzip": GZipDecoder,111 b"deflate": DeflateDecoder,112 b"identity": IdentityDecoder,113 b"br": BrotliDecoder,114}115116117if brotli is None:118 SUPPORTED_DECODERS.pop(b"br") # pragma: nocover
added:tests/test_decoding.py+79 added
1import zlib23import brotli4import pytest56import httpcore789def 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()1314 headers = [(b"Content-Encoding", b"deflate")]15 response = httpcore.Response(200, headers=headers, body=compressed_body)16 assert response.body == body171819def 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()2324 headers = [(b"Content-Encoding", b"gzip")]25 response = httpcore.Response(200, headers=headers, body=compressed_body)26 assert response.body == body272829def test_brotli():30 body = b"test 123"31 compressed_body = brotli.compress(body)3233 headers = [(b"Content-Encoding", b"br")]34 response = httpcore.Response(200, headers=headers, body=compressed_body)35 assert response.body == body363738def test_multi():39 body = b"test 123"4041 deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)42 compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()4344 gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)45 compressed_body = (46 gzip_compressor.compress(compressed_body) + gzip_compressor.flush()47 )4849 headers = [(b"Content-Encoding", b"deflate, gzip")]50 response = httpcore.Response(200, headers=headers, body=compressed_body)51 assert response.body == body525354def test_multi_with_identity():55 body = b"test 123"56 compressed_body = brotli.compress(body)5758 headers = [(b"Content-Encoding", b"br, identity")]59 response = httpcore.Response(200, headers=headers, body=compressed_body)60 assert response.body == body6162 headers = [(b"Content-Encoding", b"identity, br")]63 response = httpcore.Response(200, headers=headers, body=compressed_body)64 assert response.body == body656667@pytest.mark.asyncio68async def test_streaming():69 body = b"test 123"70 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)7172 async def compress(body):73 yield compressor.compress(body)74 yield compressor.flush()7576 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() == body
modified:requirements.txt+4 added
1certifi2h1134# Optional5brotlipy678# Testing9autoflake10black11codecov
6 unmodified lines