Skip to content
Myr

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

15 files+148 added−26 removed

modified:docs/index.md+3 added-2 removed
modified:docs/quickstart.md+4 added-2 removed
98 unmodified lines
99```100101Any `gzip` and `deflate` HTTP response encodings will automatically102be decoded for you. If `brotlipy` is installed, then the `brotli` response103encoding will also be supported.103encoding will be supported. If `zstandard` is installed, then `zstd`104response encodings will also be supported.105106For example, to create an image from binary data returned by a request, you can use the following code:107108```pycon
253 unmodified lines
362```363364HTTPX will use universal line endings, normalising all cases to `\n`.365365In 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.366In 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` will367not be automatically decoded.368369```pycon370>>> with httpx.stream("GET", "https://www.example.com") as r:371... for chunk in r.iter_raw():
173 unmodified lines
modified:httpx/_compat.py+21 added
1 unmodified line
2The _compat module is used for code which requires branching between different3Python environments. It is excluded from the code coverage checks.4"""56import re7import ssl8import sys9from types import ModuleType10from typing import Optional1112# 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 lines
19 import brotli20 except ImportError:21 brotli = None2223# Zstandard support is optional24zstd: Optional[ModuleType] = None25try:26 import zstandard as zstd27except (AttributeError, ImportError, ValueError): # Defensive:28 zstd = None29else: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 = None394041if sys.version_info >= (3, 10) or ssl.OPENSSL_VERSION_INFO >= (1, 1, 0, 7):4243 def set_minimum_tls_version_1_2(context: ssl.SSLContext) -> None:44 # The OP_NO_SSL* and OP_NO_TLS* become deprecated in favor of
19 unmodified lines
modified:httpx/_decoders.py+42 added-1 removed
9 unmodified lines
10import io11import typing12import zlib1314from ._compat import brotli14from ._compat import brotli, zstd15from ._exceptions import DecodingError161718class ContentDecoder:
120 unmodified lines
139 except brotli.error as exc: # pragma: no cover140 raise DecodingError(str(exc)) from exc141142143class ZStandardDecoder(ContentDecoder):144 """145 Handle 'zstd' RFC 8878 decoding.146147 Requires `pip install zstandard`.148 Can be installed as a dependency of httpx using `pip install httpx[zstd]`.149 """150151 # 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 None158159 self.decompressor = zstd.ZstdDecompressor().decompressobj()160161 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()173174 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)179180181class MultiDecoder(ContentDecoder):182 """183 Handle the case where multiple encodings have been applied.184 """
175 unmodified lines
360 "identity": IdentityDecoder,361 "gzip": GZipDecoder,362 "deflate": DeflateDecoder,363 "br": BrotliDecoder,364 "zstd": ZStandardDecoder,365}366367368if brotli is None:369 SUPPORTED_DECODERS.pop("br") # pragma: no cover370if zstd is None:371 SUPPORTED_DECODERS.pop("zstd") # pragma: no cover
modified:httpx/_models.py+2 added-2 removed
816 unmodified lines
817818 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 lines
917 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 lines
modified:tests/client/test_client.py+1 added-1 removed
355 unmodified lines
356 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 lines
modified:tests/client/test_event_hooks.py+6 added-6 removed
34 unmodified lines
35 "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 lines
86 "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 lines
143 "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 lines
158 "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 lines
200 "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 lines
215 "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 lines
modified:tests/client/test_headers.py+8 added-8 removed
32 unmodified lines
33 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 lines
55 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 lines
77 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 lines
99 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 lines
110 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 lines
163 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 lines
191 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 lines
214 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 lines
modified:tests/test_asgi.py+1 added-1 removed
155 unmodified lines
156 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 lines
modified:tests/test_decoders.py+49 added
1from __future__ import annotations23import io4import typing5import zlib67import chardet8import pytest9import zstandard as zstd1011import httpx1213
60 unmodified lines
74 )75 assert response.content == body767778def test_zstd():79 body = b"test 123"80 compressed_body = zstd.compress(body)8182 headers = [(b"Content-Encoding", b"zstd")]83 response = httpx.Response(84 200,85 headers=headers,86 content=compressed_body,87 )88 assert response.content == body899091def test_zstd_decoding_error():92 compressed_body = "this_is_not_zstd_compressed_data"9394 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 )101102103def 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)118119 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"123124125def test_multi():126 body = b"test 123"127128 deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
208 unmodified lines
modified:tests/test_main.py+2 added-2 removed
127 unmodified lines
128 "* 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 lines
153 "* 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 lines
modified:CHANGELOG.md+4 added
4 unmodified lines
5The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).67## Unreleased89## Added1011* Support for `zstd` content decoding using the python `zstandard` package is added. Installable using `httpx[zstd]`. (#3139)1213### Fixed1415* Fix `app` type signature in `ASGITransport`. (#3109)16
1077 unmodified lines
modified:pyproject.toml+3 added
50 unmodified lines
51]52socks = [53 "socksio==1.*",54]55zstd = [56 "zstandard>=0.18.0",57]5859[project.scripts]60httpx = "httpx:main"61
72 unmodified lines
modified:README.md+1 added
136 unmodified lines
137* `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]`)*142143A huge amount of credit is due to `requests` for the API layout that144much of this work follows, as well as to `urllib3` for plenty of design145inspiration around the lower-level networking details.
4 unmodified lines
modified: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]67# Optional charset auto-detection8# Used in our test cases9chardet==5.2.0
20 unmodified lines