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
Provenance
- Commit
d514312- Tree
684b2bd- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
acb5e6a
7 files changed+42 added−25 removed
modified:docs/index.md+1 added-1 removed
114 unmodified linesExpand all11511611711811911912012112212324 unmodified lines114 unmodified linesExpand all* `rfc3986` - URL parsing & normalization. * `idna` - Internationalized domain name support.* `sniffio` - Async library autodetection.* `async_generator` - Backport support for `contextlib.asynccontextmanager`. *(Only required for Python 3.6)** `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional)** `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional)*
A huge amount of credit is due to `requests` for the API layout thatmuch of this work follows, as well as to `urllib3` for plenty of designinspiration around the lower-level networking details.24 unmodified linesmodified:httpx/_compat.py+11 added
10 unmodified lines11 from contextlib import asynccontextmanager # type: ignore12 except ImportError:13 from async_generator import asynccontextmanager # type: ignore # noqa14 15+# 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.18+try:19+ import brotlicffi as brotli20+except ImportError: # pragma: nocover21+ try:22+ import brotli23+ except ImportError:24+ brotli = None25+26 if 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 linesmodified:httpx/_decoders.py+18 added-15 removed
6 unmodified lines7 import io8 import typing9 import zlib10 11+from ._compat import brotli12 from ._exceptions import DecodingError13 13-try:14- import brotlicffi15-except ImportError: # pragma: nocover16- brotlicffi = None14 18-15 class ContentDecoder:16 def decode(self, data: bytes) -> bytes:17 raise NotImplementedError() # pragma: nocover18 75 unmodified lines94 name. The top branches are for 'brotlipy' and bottom branches for 'Brotli'95 """96 97 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 None104 109- 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: nocover113 114 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 exc122 123 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.129+130+ # 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 exc137 138 139 class MultiDecoder(ContentDecoder):188 unmodified lines328 "br": BrotliDecoder,329 }330 331 329-if brotlicffi is None:332+if brotli is None:333 SUPPORTED_DECODERS.pop("br") # pragma: nocovermodified:tests/models/test_responses.py+3 added-3 removed
1 import json2 import pickle3 4-import brotlicffi4 import pytest5 6 import httpx7+from httpx._compat import brotli8 9 10 class StreamingBody:11 def __iter__(self):785 unmodified lines797 @pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))798 def 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 lines818 @pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))819 def 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)825 826 78 unmodified linesmodified:tests/test_decoders.py+4 added-4 removed
1 import zlib2 3-import brotlicffi3 import pytest4 5 import httpx6+from httpx._compat import brotli7 from httpx._decoders import (8 BrotliDecoder,9 ByteChunker,10 DeflateDecoder,57 unmodified lines68 69 70 def test_brotli():71 body = b"test 123"72- compressed_body = brotlicffi.compress(body)72+ compressed_body = brotli.compress(body)73 74 headers = [(b"Content-Encoding", b"br")]75 response = httpx.Response(76 200,24 unmodified lines101 102 103 def test_multi_with_identity():104 body = b"test 123"105- compressed_body = brotlicffi.compress(body)105+ compressed_body = brotli.compress(body)106 107 headers = [(b"Content-Encoding", b"br, identity")]108 response = httpx.Response(109 200,54 unmodified lines164 @pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))165 def 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 linesmodified:README.md+1 added-1 removed
122 unmodified lines123 * `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)*128 129 A huge amount of credit is due to `requests` for the API layout that130 much of this work follows, as well as to `urllib3` for plenty of design131 inspiration around the lower-level networking details.3 unmodified linesmodified:setup.py+4 added-1 removed
63 unmodified lines64 "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