Skip to content
Myr

Use either brotli or brotlicffi. (#1618)

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

* Use either brotli (recommended for CPython) or brotlicffi (Recommended for PyPy and others) * Add comments in places where we switch behaviour depending on brotli/brotlicffi

authored by Tom Christie · committed by GitHub · parent acb5e6a · Browse files · 7 files+42 added−25 removed
This commit

State

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

Trailers

  • Co-authored-by: Florimond Manca <florimond.manca@gmail.com>

Diff stats

7 files+42 added−25 removed

  • tests:+7 added−7 removed
  • other:+35 added−18 removed

7 files+42 added−25 removed

modified:docs/index.md+1 added-1 removed
modified:httpx/_compat.py+11 added
10 unmodified lines
11 from contextlib import asynccontextmanager # type: ignore12except ImportError:13 from async_generator import asynccontextmanager # type: ignore # noqa1415# Brotli support is optional16# The C bindings in `brotli` are recommended for CPython.17# The CFFI bindings in `brotlicffi` are recommended for PyPy and everything else.18try:19 import brotlicffi as brotli20except ImportError: # pragma: nocover21 try:22 import brotli23 except ImportError:24 brotli = None2526if sys.version_info >= (3, 10) or (27 sys.version_info >= (3, 7) and ssl.OPENSSL_VERSION_INFO >= (1, 1, 0, 7)28):29
19 unmodified lines
modified:httpx/_decoders.py+18 added-15 removed
6 unmodified lines
7import io8import typing9import zlib1011from ._compat import brotli12from ._exceptions import DecodingError1313try:14 import brotlicffi15except ImportError: # pragma: nocover16 brotlicffi = None141815class ContentDecoder:16 def decode(self, data: bytes) -> bytes:17 raise NotImplementedError() # pragma: nocover18
75 unmodified lines
94 name. The top branches are for 'brotlipy' and bottom branches for 'Brotli'95 """9697 def __init__(self) -> None:102 if brotlicffi is None: # pragma: nocover98 if brotli is None: # pragma: nocover99 raise ImportError(104 "Using 'BrotliDecoder', but the 'brotlicffi' library "105 "is not installed."100 "Using 'BrotliDecoder', but neither of the 'brotlicffi' or 'brotli' "101 "packages have been installed. "102 "Make sure to install httpx using `pip install httpx[brotli]`."103 ) from None104109 self.decompressor = brotlicffi.Decompressor()105 self.decompressor = brotli.Decompressor()106 self.seen_data = False107 if hasattr(self.decompressor, "decompress"):108 # The 'brotlicffi' package.112 self._decompress = self.decompressor.decompress109 self._decompress = self.decompressor.decompress # pragma: nocover110 else:111 # The 'brotli' package.112 self._decompress = self.decompressor.process # pragma: nocover113114 def decode(self, data: bytes) -> bytes:115 if not data:116 return b""117 self.seen_data = True118 try:121 return self.decompressor.decompress(data)122 except brotlicffi.Error as exc:119 return self._decompress(data)120 except brotli.error as exc:121 raise DecodingError(str(exc)) from exc122123 def flush(self) -> bytes:124 if not self.seen_data:125 return b""126 try:127 if hasattr(self.decompressor, "finish"):128 # Only available in the 'brotlicffi' package.129130 # As the decompressor decompresses eagerly, this131 # will never actually emit any data. However, it will potentially throw132 # errors if a truncated or damaged data stream has been used.130 self.decompressor.finish()133 self.decompressor.finish() # pragma: nocover134 return b""132 except brotlicffi.Error as exc: # pragma: nocover135 except brotli.error as exc: # pragma: nocover136 raise DecodingError(str(exc)) from exc137138139class MultiDecoder(ContentDecoder):
188 unmodified lines
328 "br": BrotliDecoder,329}330331329if brotlicffi is None:332if brotli is None:333 SUPPORTED_DECODERS.pop("br") # pragma: nocover
modified:tests/models/test_responses.py+3 added-3 removed
1import json2import pickle34import brotlicffi4import pytest56import httpx7from httpx._compat import brotli8910class StreamingBody:11 def __iter__(self):
785 unmodified lines
797@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))798def test_decode_error_with_request(header_value):799 headers = [(b"Content-Encoding", header_value)]800 body = b"test 123"801 compressed_body = brotlicffi.compress(body)[3:]801 compressed_body = brotli.compress(body)[3:]802 with pytest.raises(httpx.DecodingError):803 httpx.Response(804 200,805 headers=headers,
12 unmodified lines
818@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))819def test_value_error_without_request(header_value):820 headers = [(b"Content-Encoding", header_value)]821 body = b"test 123"822 compressed_body = brotlicffi.compress(body)[3:]822 compressed_body = brotli.compress(body)[3:]823 with pytest.raises(httpx.DecodingError):824 httpx.Response(200, headers=headers, content=compressed_body)825826
78 unmodified lines
modified:tests/test_decoders.py+4 added-4 removed
1import zlib23import brotlicffi3import pytest45import httpx6from httpx._compat import brotli7from httpx._decoders import (8 BrotliDecoder,9 ByteChunker,10 DeflateDecoder,
57 unmodified lines
686970def test_brotli():71 body = b"test 123"72 compressed_body = brotlicffi.compress(body)72 compressed_body = brotli.compress(body)7374 headers = [(b"Content-Encoding", b"br")]75 response = httpx.Response(76 200,
24 unmodified lines
101102103def test_multi_with_identity():104 body = b"test 123"105 compressed_body = brotlicffi.compress(body)105 compressed_body = brotli.compress(body)106107 headers = [(b"Content-Encoding", b"br, identity")]108 response = httpx.Response(109 200,
54 unmodified lines
164@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))165def test_decoding_errors(header_value):166 headers = [(b"Content-Encoding", header_value)]167 body = b"test 123"168 compressed_body = brotlicffi.compress(body)[3:]168 compressed_body = brotli.compress(body)[3:]169 with pytest.raises(httpx.DecodingError):170 request = httpx.Request("GET", "https://example.org")171 httpx.Response(200, headers=headers, content=compressed_body, request=request)172
185 unmodified lines
modified:README.md+1 added-1 removed
122 unmodified lines
123* `rfc3986` - URL parsing & normalization.124 * `idna` - Internationalized domain name support.125* `sniffio` - Async library autodetection.126* `async_generator` - Backport support for `contextlib.asynccontextmanager`. *(Only required for Python 3.6)*127* `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional)*127* `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional)*128129A huge amount of credit is due to `requests` for the API layout that130much of this work follows, as well as to `urllib3` for plenty of design131inspiration around the lower-level networking details.
3 unmodified lines
modified:setup.py+4 added-1 removed
63 unmodified lines
64 "async_generator; python_version < '3.7'"65 ],66 extras_require={67 "http2": "h2>=3,<5",68 "brotli": "brotlicffi==1.*",68 "brotli": [69 "brotli; platform_python_implementation == 'CPython'",70 "brotlicffi; platform_python_implementation != 'CPython'"71 ],72 },73 classifiers=[74 "Development Status :: 4 - Beta",75 "Environment :: Web Environment",
15 unmodified lines