Add support for zstd decoding (#3139)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This adds support for zstd decoding using the python package zstandard. This is similar to how it is implemented in urllib3. I also chose the optional installation option httpx[zstd] to mimic the same option in urllib3. zstd decoding is similar to brotli, but in benchmarks it is supposed to be even faster. The zstd compression is described in RFC 8878. See https://github.com/encode/httpx/discussions/1986
authored by Michiel W. Beijen · committed by GitHub · parent 7df47ce · Browse files · 15 files·+148 added−26 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: Kamil Monicz <kamil@monicz.dev>
Diff stats
15 files+148 added−26 removed
- tests:+67 added−18 removed
- other:+81 added−8 removed
Provenance
- Commit
392dbe4- Tree
2607b9e- Author
Michiel W. Beijen <mb@x14.nl>- Committer
GitHub <noreply@github.com>- Parent
7df47ce
15 files changed+148 added−26 removed
modified:docs/index.md+3 added-2 removed
117 unmodified linesExpand all11811912012112212312412512611 unmodified lines138139140141141142143144144145146147148149150117 unmodified linesExpand all* `socksio` - SOCKS proxy support. *(Optional, with `httpx[socks]`)** `rich` - Rich terminal support. *(Optional, with `httpx[cli]`)** `click` - Command line client support. *(Optional, with `httpx[cli]`)** `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx[brotli]`)** `zstandard` - Decoding for "zstd" compressed responses. *(Optional, with `httpx[zstd]`)*
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.11 unmodified lines```shell$ pip install httpx[http2]```
To include the optional brotli decoder support, use:To include the optional brotli and zstandard decoders support, use:
```shell$ pip install httpx[brotli]$ pip install httpx[brotli,zstd]```
HTTPX requires Python 3.8+
[sync-support]: https://github.com/encode/httpx/issues/572modified:docs/quickstart.md+4 added-2 removed
98 unmodified lines99 ```100 101 Any `gzip` and `deflate` HTTP response encodings will automatically102 be decoded for you. If `brotlipy` is installed, then the `brotli` response103-encoding will also be supported.103+encoding will be supported. If `zstandard` is installed, then `zstd`104+response encodings will also be supported.105 106 For example, to create an image from binary data returned by a request, you can use the following code:107 108 ```pycon253 unmodified lines362 ```363 364 HTTPX will use universal line endings, normalising all cases to `\n`.365 365-In some cases you might want to access the raw bytes on the response without applying any HTTP content decoding. In this case any content encoding that the web server has applied such as `gzip`, `deflate`, or `brotli` will not be automatically decoded.366+In some cases you might want to access the raw bytes on the response without applying any HTTP content decoding. In this case any content encoding that the web server has applied such as `gzip`, `deflate`, `brotli`, or `zstd` will367+not be automatically decoded.368 369 ```pycon370 >>> with httpx.stream("GET", "https://www.example.com") as r:371 ... for chunk in r.iter_raw():173 unmodified linesmodified:httpx/_compat.py+21 added
1 unmodified line2 The _compat module is used for code which requires branching between different3 Python environments. It is excluded from the code coverage checks.4 """5 6+import re7 import ssl8 import sys9+from types import ModuleType10+from typing import Optional11 12 # Brotli support is optional13 # The C bindings in `brotli` are recommended for CPython.14 # The CFFI bindings in `brotlicffi` are recommended for PyPy and everything else.4 unmodified lines19 import brotli20 except ImportError:21 brotli = None22 23+# Zstandard support is optional24+zstd: Optional[ModuleType] = None25+try:26+ import zstandard as zstd27+except (AttributeError, ImportError, ValueError): # Defensive:28+ zstd = None29+else:30+ # The package 'zstandard' added the 'eof' property starting31+ # in v0.18.0 which we require to ensure a complete and32+ # valid zstd stream was fed into the ZstdDecoder.33+ # See: https://github.com/urllib3/urllib3/pull/262434+ _zstd_version = tuple(35+ map(int, re.search(r"^([0-9]+)\.([0-9]+)", zstd.__version__).groups()) # type: ignore[union-attr]36+ )37+ if _zstd_version < (0, 18): # Defensive:38+ zstd = None39+40+41 if sys.version_info >= (3, 10) or ssl.OPENSSL_VERSION_INFO >= (1, 1, 0, 7):42 43 def set_minimum_tls_version_1_2(context: ssl.SSLContext) -> None:44 # The OP_NO_SSL* and OP_NO_TLS* become deprecated in favor of19 unmodified linesmodified:httpx/_decoders.py+42 added-1 removed
9 unmodified lines10 import io11 import typing12 import zlib13 14-from ._compat import brotli14+from ._compat import brotli, zstd15 from ._exceptions import DecodingError16 17 18 class ContentDecoder:120 unmodified lines139 except brotli.error as exc: # pragma: no cover140 raise DecodingError(str(exc)) from exc141 142 143+class ZStandardDecoder(ContentDecoder):144+ """145+ Handle 'zstd' RFC 8878 decoding.146+147+ Requires `pip install zstandard`.148+ Can be installed as a dependency of httpx using `pip install httpx[zstd]`.149+ """150+151+ # inspired by the ZstdDecoder implementation in urllib3152+ def __init__(self) -> None:153+ if zstd is None: # pragma: no cover154+ raise ImportError(155+ "Using 'ZStandardDecoder', ..."156+ "Make sure to install httpx using `pip install httpx[zstd]`."157+ ) from None158+159+ self.decompressor = zstd.ZstdDecompressor().decompressobj()160+161+ def decode(self, data: bytes) -> bytes:162+ assert zstd is not None163+ output = io.BytesIO()164+ try:165+ output.write(self.decompressor.decompress(data))166+ while self.decompressor.eof and self.decompressor.unused_data:167+ unused_data = self.decompressor.unused_data168+ self.decompressor = zstd.ZstdDecompressor().decompressobj()169+ output.write(self.decompressor.decompress(unused_data))170+ except zstd.ZstdError as exc:171+ raise DecodingError(str(exc)) from exc172+ return output.getvalue()173+174+ def flush(self) -> bytes:175+ ret = self.decompressor.flush() # note: this is a no-op176+ if not self.decompressor.eof:177+ raise DecodingError("Zstandard data is incomplete") # pragma: no cover178+ return bytes(ret)179+180+181 class MultiDecoder(ContentDecoder):182 """183 Handle the case where multiple encodings have been applied.184 """175 unmodified lines360 "identity": IdentityDecoder,361 "gzip": GZipDecoder,362 "deflate": DeflateDecoder,363 "br": BrotliDecoder,364+ "zstd": ZStandardDecoder,365 }366 367 368 if brotli is None:369 SUPPORTED_DECODERS.pop("br") # pragma: no cover370+if zstd is None:371+ SUPPORTED_DECODERS.pop("zstd") # pragma: no covermodified:httpx/_models.py+2 added-2 removed
816 unmodified lines817 818 def iter_bytes(self, chunk_size: int | None = None) -> typing.Iterator[bytes]:819 """820 A byte-iterator over the decoded response content.821- This allows us to handle gzip, deflate, and brotli encoded responses.821+ This allows us to handle gzip, deflate, brotli, and zstd encoded responses.822 """823 if hasattr(self, "_content"):824 chunk_size = len(self._content) if chunk_size is None else chunk_size825 for i in range(0, len(self._content), max(chunk_size, 1)):91 unmodified lines917 self, chunk_size: int | None = None918 ) -> typing.AsyncIterator[bytes]:919 """920 A byte-iterator over the decoded response content.921- This allows us to handle gzip, deflate, and brotli encoded responses.921+ This allows us to handle gzip, deflate, brotli, and zstd encoded responses.922 """923 if hasattr(self, "_content"):924 chunk_size = len(self._content) if chunk_size is None else chunk_size925 for i in range(0, len(self._content), max(chunk_size, 1)):286 unmodified linesmodified:tests/client/test_client.py+1 added-1 removed
355 unmodified lines356 assert response.status_code == 200357 assert response.json() == [358 ["Host", "example.org"],359 ["Accept", "*/*"],360- ["Accept-Encoding", "gzip, deflate, br"],360+ ["Accept-Encoding", "gzip, deflate, br, zstd"],361 ["Connection", "keep-alive"],362 ["User-Agent", f"python-httpx/{httpx.__version__}"],363 ["Example-Header", "example-value"],364 ]98 unmodified linesmodified:tests/client/test_event_hooks.py+6 added-6 removed
34 unmodified lines35 "headers": {36 "host": "127.0.0.1:8000",37 "user-agent": f"python-httpx/{httpx.__version__}",38 "accept": "*/*",39- "accept-encoding": "gzip, deflate, br",39+ "accept-encoding": "gzip, deflate, br, zstd",40 "connection": "keep-alive",41 "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",42 },43 },42 unmodified lines86 "headers": {87 "host": "127.0.0.1:8000",88 "user-agent": f"python-httpx/{httpx.__version__}",89 "accept": "*/*",90- "accept-encoding": "gzip, deflate, br",90+ "accept-encoding": "gzip, deflate, br, zstd",91 "connection": "keep-alive",92 "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",93 },94 },48 unmodified lines143 "headers": {144 "host": "127.0.0.1:8000",145 "user-agent": f"python-httpx/{httpx.__version__}",146 "accept": "*/*",147- "accept-encoding": "gzip, deflate, br",147+ "accept-encoding": "gzip, deflate, br, zstd",148 "connection": "keep-alive",149 "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",150 },151 },6 unmodified lines158 "headers": {159 "host": "127.0.0.1:8000",160 "user-agent": f"python-httpx/{httpx.__version__}",161 "accept": "*/*",162- "accept-encoding": "gzip, deflate, br",162+ "accept-encoding": "gzip, deflate, br, zstd",163 "connection": "keep-alive",164 "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",165 },166 },33 unmodified lines200 "headers": {201 "host": "127.0.0.1:8000",202 "user-agent": f"python-httpx/{httpx.__version__}",203 "accept": "*/*",204- "accept-encoding": "gzip, deflate, br",204+ "accept-encoding": "gzip, deflate, br, zstd",205 "connection": "keep-alive",206 "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",207 },208 },6 unmodified lines215 "headers": {216 "host": "127.0.0.1:8000",217 "user-agent": f"python-httpx/{httpx.__version__}",218 "accept": "*/*",219- "accept-encoding": "gzip, deflate, br",219+ "accept-encoding": "gzip, deflate, br, zstd",220 "connection": "keep-alive",221 "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",222 },223 },5 unmodified linesmodified:tests/client/test_headers.py+8 added-8 removed
32 unmodified lines33 assert response.status_code == 20034 assert response.json() == {35 "headers": {36 "accept": "*/*",37- "accept-encoding": "gzip, deflate, br",37+ "accept-encoding": "gzip, deflate, br, zstd",38 "connection": "keep-alive",39 "example-header": "example-value",40 "host": "example.org",41 "user-agent": f"python-httpx/{httpx.__version__}",13 unmodified lines55 assert response.status_code == 20056 assert response.json() == {57 "headers": {58 "accept": "*/*",59- "accept-encoding": "gzip, deflate, br",59+ "accept-encoding": "gzip, deflate, br, zstd",60 "connection": "keep-alive",61 "host": "example.org",62 "user-agent": "python-myclient/0.2.1",63 "x-auth-token": "FooBarBazToken",13 unmodified lines77 assert response.status_code == 20078 assert response.json() == {79 "headers": {80 "accept": "*/*",81- "accept-encoding": "gzip, deflate, br",81+ "accept-encoding": "gzip, deflate, br, zstd",82 "connection": "keep-alive",83 "host": "example.org",84 "user-agent": f"python-httpx/{httpx.__version__}",85 "x-auth-token": "BazToken",13 unmodified lines99 assert first_response.status_code == 200100 assert first_response.json() == {101 "headers": {102 "accept": "*/*",103- "accept-encoding": "gzip, deflate, br",103+ "accept-encoding": "gzip, deflate, br, zstd",104 "connection": "keep-alive",105 "host": "example.org",106 "user-agent": f"python-httpx/{httpx.__version__}",107 }2 unmodified lines110 assert second_response.status_code == 200111 assert second_response.json() == {112 "headers": {113 "accept": "*/*",114- "accept-encoding": "gzip, deflate, br",114+ "accept-encoding": "gzip, deflate, br, zstd",115 "another-header": "AThing",116 "connection": "keep-alive",117 "host": "example.org",118 "user-agent": "python-myclient/0.2.1",44 unmodified lines163 assert response.status_code == 200164 assert response.json() == {165 "headers": {166 "accept": "*/*",167- "accept-encoding": "gzip, deflate, br",167+ "accept-encoding": "gzip, deflate, br, zstd",168 "connection": "keep-alive",169 "host": "example.org",170 }171 }19 unmodified lines191 assert response.status_code == 200192 assert response.json() == {193 "headers": {194 "accept": "*/*",195- "accept-encoding": "gzip, deflate, br",195+ "accept-encoding": "gzip, deflate, br, zstd",196 "connection": "keep-alive",197 "host": "example.org",198 "user-agent": f"python-httpx/{httpx.__version__}",199 "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",14 unmodified lines214 assert response.status_code == 200215 assert response.json() == {216 "headers": {217 "accept": "*/*",218- "accept-encoding": "gzip, deflate, br",218+ "accept-encoding": "gzip, deflate, br, zstd",219 "connection": "keep-alive",220 "host": "example.org:123",221 "user-agent": f"python-httpx/{httpx.__version__}",222 "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",7 unmodified linesmodified:tests/test_asgi.py+1 added-1 removed
155 unmodified lines156 assert response.json() == {157 "headers": [158 ["host", "www.example.org"],159 ["accept", "*/*"],160- ["accept-encoding", "gzip, deflate, br"],160+ ["accept-encoding", "gzip, deflate, br, zstd"],161 ["connection", "keep-alive"],162 ["user-agent", f"python-httpx/{httpx.__version__}"],163 ]164 }70 unmodified linesmodified:tests/test_decoders.py+49 added
1 from __future__ import annotations2 3+import io4 import typing5 import zlib6 7 import chardet8 import pytest9+import zstandard as zstd10 11 import httpx12 13 60 unmodified lines74 )75 assert response.content == body76 77 78+def test_zstd():79+ body = b"test 123"80+ compressed_body = zstd.compress(body)81+82+ headers = [(b"Content-Encoding", b"zstd")]83+ response = httpx.Response(84+ 200,85+ headers=headers,86+ content=compressed_body,87+ )88+ assert response.content == body89+90+91+def test_zstd_decoding_error():92+ compressed_body = "this_is_not_zstd_compressed_data"93+94+ headers = [(b"Content-Encoding", b"zstd")]95+ with pytest.raises(httpx.DecodingError):96+ httpx.Response(97+ 200,98+ headers=headers,99+ content=compressed_body,100+ )101+102+103+def test_zstd_multiframe():104+ # test inspired by urllib3 test suite105+ data = (106+ # Zstandard frame107+ zstd.compress(b"foo")108+ # skippable frame (must be ignored)109+ + bytes.fromhex(110+ "50 2A 4D 18" # Magic_Number (little-endian)111+ "07 00 00 00" # Frame_Size (little-endian)112+ "00 00 00 00 00 00 00" # User_Data113+ )114+ # Zstandard frame115+ + zstd.compress(b"bar")116+ )117+ compressed_body = io.BytesIO(data)118+119+ headers = [(b"Content-Encoding", b"zstd")]120+ response = httpx.Response(200, headers=headers, content=compressed_body)121+ response.read()122+ assert response.content == b"foobar"123+124+125 def test_multi():126 body = b"test 123"127 128 deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)208 unmodified linesmodified:tests/test_main.py+2 added-2 removed
127 unmodified lines128 "* Connected to '127.0.0.1' on port 8000",129 "GET / HTTP/1.1",130 f"Host: {server.url.netloc.decode('ascii')}",131 "Accept: */*",132- "Accept-Encoding: gzip, deflate, br",132+ "Accept-Encoding: gzip, deflate, br, zstd",133 "Connection: keep-alive",134 f"User-Agent: python-httpx/{httpx.__version__}",135 "",136 "HTTP/1.1 200 OK",16 unmodified lines153 "* Connected to '127.0.0.1' on port 8000",154 "GET / HTTP/1.1",155 f"Host: {server.url.netloc.decode('ascii')}",156 "Accept: */*",157- "Accept-Encoding: gzip, deflate, br",157+ "Accept-Encoding: gzip, deflate, br, zstd",158 "Connection: keep-alive",159 f"User-Agent: python-httpx/{httpx.__version__}",160 "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=",161 "",26 unmodified linesmodified:CHANGELOG.md+4 added
4 unmodified lines5 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).6 7 ## Unreleased8 9+## Added10+11+* Support for `zstd` content decoding using the python `zstandard` package is added. Installable using `httpx[zstd]`. (#3139)12+13 ### Fixed14 15 * Fix `app` type signature in `ASGITransport`. (#3109)16 1077 unmodified linesmodified:pyproject.toml+3 added
50 unmodified lines51 ]52 socks = [53 "socksio==1.*",54 ]55+zstd = [56+ "zstandard>=0.18.0",57+]58 59 [project.scripts]60 httpx = "httpx:main"61 72 unmodified linesmodified:README.md+1 added
136 unmodified lines137 * `socksio` - SOCKS proxy support. *(Optional, with `httpx[socks]`)*138 * `rich` - Rich terminal support. *(Optional, with `httpx[cli]`)*139 * `click` - Command line client support. *(Optional, with `httpx[cli]`)*140 * `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx[brotli]`)*141+* `zstandard` - Decoding for "zstd" compressed responses. *(Optional, with `httpx[zstd]`)*142 143 A huge amount of credit is due to `requests` for the API layout that144 much of this work follows, as well as to `urllib3` for plenty of design145 inspiration around the lower-level networking details.4 unmodified linesmodified:requirements.txt+1 added-1 removed
1 # We're pinning our tooling, because it's an environment we can strictly control.2 # On the other hand, we're not pinning package dependencies, because our tests3 # needs to pass with the latest version of the packages.4 # Reference: https://github.com/encode/httpx/pull/1721#discussion_r6612415885--e .[brotli,cli,http2,socks]5+-e .[brotli,cli,http2,socks,zstd]6 7 # Optional charset auto-detection8 # Used in our test cases9 chardet==5.2.020 unmodified lines