Skip to content
Myr

Support both zlib and deflate encodings (#758)

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

* Support both zlib and deflate encodings * Helpful test docstrings

authored by Tom Christie · committed by GitHub · parent 956129f · Browse files · 2 files+28 added−1 removed
This commit

State

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

Diff stats

2 files+28 added−1 removed

  • tests:+21 added−0 removed
  • other:+7 added−1 removed

2 files+28 added−1 removed

modified:httpx/decoders.py+7 added-1 removed
43 unmodified lines
44 See: https://stackoverflow.com/questions/183869945 """4647 def __init__(self) -> None:48 self.first_attempt = True48 self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)49 self.decompressor = zlib.decompressobj()5051 def decode(self, data: bytes) -> bytes:52 was_first_attempt = self.first_attempt53 self.first_attempt = False54 try:55 return self.decompressor.decompress(data)56 except zlib.error as exc:57 if was_first_attempt:58 self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)59 return self.decode(data)60 raise DecodingError from exc6162 def flush(self) -> bytes:63 try:
227 unmodified lines
modified:tests/test_decoders.py+21 added
16 unmodified lines
17REQUEST = httpx.Request("GET", "https://example.org")181920def test_deflate():21 """22 Deflate encoding may use either 'zlib' or 'deflate' in the wild.2324 https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129725 """26 body = b"test 123"27 compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)28 compressed_body = compressor.compress(body) + compressor.flush()29
3 unmodified lines
33 )34 assert response.content == body353637def test_zlib():38 """39 Deflate encoding may use either 'zlib' or 'deflate' in the wild.4041 https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129742 """43 body = b"test 123"44 compressed_body = zlib.compress(body)4546 headers = [(b"Content-Encoding", b"deflate")]47 response = httpx.Response(48 200, headers=headers, content=compressed_body, request=REQUEST49 )50 assert response.content == body515253def test_gzip():54 body = b"test 123"55 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)56 compressed_body = compressor.compress(body) + compressor.flush()
208 unmodified lines