Support for `chunk_size` (#1277)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Support iter_raw(chunk_size=...) and aiter_raw(chunk_size=...) * Unit tests for ByteChunker * Support iter_bytes(chunk_size=...) * Add TextChunker * Support iter_text(chunk_size=...) * Fix merge with master
authored by Tom Christie · committed by GitHub · parent c4d2e6f · Browse files · 4 files·+293 added−30 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
4 files+293 added−30 removed
- tests:+140 added−4 removed
- other:+153 added−26 removed
Provenance
- Commit
27df5e4- Tree
09aa56b- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
c4d2e6f
4 files changed+293 added−30 removed
modified:httpx/_decoders.py+79 added
2 unmodified lines3 4 See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding5 """6 import codecs7+import io8 import typing9 import zlib10 11 try:143 unmodified lines155 data = child.decode(data) + child.flush()156 return data157 158 159+class ByteChunker:160+ """161+ Handles returning byte content in fixed-size chunks.162+ """163+164+ def __init__(self, chunk_size: int = None) -> None:165+ self._buffer = io.BytesIO()166+ self._chunk_size = chunk_size167+168+ def decode(self, content: bytes) -> typing.List[bytes]:169+ if self._chunk_size is None:170+ return [content]171+172+ self._buffer.write(content)173+ if self._buffer.tell() >= self._chunk_size:174+ value = self._buffer.getvalue()175+ chunks = [176+ value[i : i + self._chunk_size]177+ for i in range(0, len(value), self._chunk_size)178+ ]179+ if len(chunks[-1]) == self._chunk_size:180+ self._buffer.seek(0)181+ self._buffer.truncate()182+ return chunks183+ else:184+ self._buffer.seek(0)185+ self._buffer.write(chunks[-1])186+ self._buffer.truncate()187+ return chunks[:-1]188+ else:189+ return []190+191+ def flush(self) -> typing.List[bytes]:192+ value = self._buffer.getvalue()193+ self._buffer.seek(0)194+ self._buffer.truncate()195+ return [value] if value else []196+197+198+class TextChunker:199+ """200+ Handles returning text content in fixed-size chunks.201+ """202+203+ def __init__(self, chunk_size: int = None) -> None:204+ self._buffer = io.StringIO()205+ self._chunk_size = chunk_size206+207+ def decode(self, content: str) -> typing.List[str]:208+ if self._chunk_size is None:209+ return [content]210+211+ self._buffer.write(content)212+ if self._buffer.tell() >= self._chunk_size:213+ value = self._buffer.getvalue()214+ chunks = [215+ value[i : i + self._chunk_size]216+ for i in range(0, len(value), self._chunk_size)217+ ]218+ if len(chunks[-1]) == self._chunk_size:219+ self._buffer.seek(0)220+ self._buffer.truncate()221+ return chunks222+ else:223+ self._buffer.seek(0)224+ self._buffer.write(chunks[-1])225+ self._buffer.truncate()226+ return chunks[:-1]227+ else:228+ return []229+230+ def flush(self) -> typing.List[str]:231+ value = self._buffer.getvalue()232+ self._buffer.seek(0)233+ self._buffer.truncate()234+ return [value] if value else []235+236+237 class TextDecoder:238 """239 Handles incrementally decoding bytes into text240 """127 unmodified linesmodified:httpx/_models.py+74 added-26 removed
13 unmodified lines14 15 from ._content import PlainByteStream, encode_request, encode_response16 from ._decoders import (17 SUPPORTED_DECODERS,18+ ByteChunker,19 ContentDecoder,20 IdentityDecoder,21 LineDecoder,22 MultiDecoder,23+ TextChunker,24 TextDecoder,25 )26 from ._exceptions import (27 HTTPCORE_EXC_MAP,1135 unmodified lines1163 if not hasattr(self, "_content"):1164 self._content = b"".join(self.iter_bytes())1165 return self._content1166 1165- def iter_bytes(self) -> typing.Iterator[bytes]:1167+ def iter_bytes(self, chunk_size: int = None) -> typing.Iterator[bytes]:1168 """1169 A byte-iterator over the decoded response content.1170 This allows us to handle gzip, deflate, and brotli encoded responses.1171 """1172 if hasattr(self, "_content"):1173+ chunk_size = len(self._content) if chunk_size is None else chunk_size1174+ for i in range(0, len(self._content), chunk_size):1171- yield self._content1175+ yield self._content[i : i + chunk_size]1176 else:1177 decoder = self._get_content_decoder()1178+ chunker = ByteChunker(chunk_size=chunk_size)1179 with self._wrap_decoder_errors():1175- for chunk in self.iter_raw():1176- yield decoder.decode(chunk)1177- yield decoder.flush()1180+ for raw_bytes in self.iter_raw():1181+ decoded = decoder.decode(raw_bytes)1182+ for chunk in chunker.decode(decoded):1183+ yield chunk1184+ decoded = decoder.flush()1185+ for chunk in chunker.decode(decoded):1186+ yield chunk1187+ for chunk in chunker.flush():1188+ yield chunk1189 1179- def iter_text(self) -> typing.Iterator[str]:1190+ def iter_text(self, chunk_size: int = None) -> typing.Iterator[str]:1191 """1192 A str-iterator over the decoded response content1193 that handles both gzip, deflate, etc but also detects the content's1194 string encoding.1195 """1196 decoder = TextDecoder(encoding=self.encoding)1197+ chunker = TextChunker(chunk_size=chunk_size)1198 with self._wrap_decoder_errors():1187- for chunk in self.iter_bytes():1188- yield decoder.decode(chunk)1189- yield decoder.flush()1199+ for byte_content in self.iter_bytes():1200+ text_content = decoder.decode(byte_content)1201+ for chunk in chunker.decode(text_content):1202+ yield chunk1203+ text_content = decoder.flush()1204+ for chunk in chunker.decode(text_content):1205+ yield chunk1206+ for chunk in chunker.flush():1207+ yield chunk1208 1209 def iter_lines(self) -> typing.Iterator[str]:1210 decoder = LineDecoder()1211 with self._wrap_decoder_errors():2 unmodified lines1214 yield line1215 for line in decoder.flush():1216 yield line1217 1200- def iter_raw(self) -> typing.Iterator[bytes]:1218+ def iter_raw(self, chunk_size: int = None) -> typing.Iterator[bytes]:1219 """1220 A byte-iterator over the raw response content.1221 """1222 if self.is_stream_consumed:4 unmodified lines1227 raise RuntimeError("Attempted to call a sync iterator on an async stream.")1228 1229 self.is_stream_consumed = True1230 self._num_bytes_downloaded = 01231+ chunker = ByteChunker(chunk_size=chunk_size)1232+1233 with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):1214- for part in self.stream:1215- self._num_bytes_downloaded += len(part)1216- yield part1234+ for raw_stream_bytes in self.stream:1235+ self._num_bytes_downloaded += len(raw_stream_bytes)1236+ for chunk in chunker.decode(raw_stream_bytes):1237+ yield chunk1238+1239+ for chunk in chunker.flush():1240+ yield chunk1241+1242 self.close()1243 1244 def close(self) -> None:1245 """12 unmodified lines1258 if not hasattr(self, "_content"):1259 self._content = b"".join([part async for part in self.aiter_bytes()])1260 return self._content1261 1237- async def aiter_bytes(self) -> typing.AsyncIterator[bytes]:1262+ async def aiter_bytes(self, chunk_size: int = None) -> typing.AsyncIterator[bytes]:1263 """1264 A byte-iterator over the decoded response content.1265 This allows us to handle gzip, deflate, and brotli encoded responses.1266 """1267 if hasattr(self, "_content"):1268+ chunk_size = len(self._content) if chunk_size is None else chunk_size1269+ for i in range(0, len(self._content), chunk_size):1243- yield self._content1270+ yield self._content[i : i + chunk_size]1271 else:1272 decoder = self._get_content_decoder()1273+ chunker = ByteChunker(chunk_size=chunk_size)1274 with self._wrap_decoder_errors():1247- async for chunk in self.aiter_raw():1248- yield decoder.decode(chunk)1249- yield decoder.flush()1275+ async for raw_bytes in self.aiter_raw():1276+ decoded = decoder.decode(raw_bytes)1277+ for chunk in chunker.decode(decoded):1278+ yield chunk1279+ decoded = decoder.flush()1280+ for chunk in chunker.decode(decoded):1281+ yield chunk1282+ for chunk in chunker.flush():1283+ yield chunk1284 1251- async def aiter_text(self) -> typing.AsyncIterator[str]:1285+ async def aiter_text(self, chunk_size: int = None) -> typing.AsyncIterator[str]:1286 """1287 A str-iterator over the decoded response content1288 that handles both gzip, deflate, etc but also detects the content's1289 string encoding.1290 """1291 decoder = TextDecoder(encoding=self.encoding)1292+ chunker = TextChunker(chunk_size=chunk_size)1293 with self._wrap_decoder_errors():1259- async for chunk in self.aiter_bytes():1260- yield decoder.decode(chunk)1261- yield decoder.flush()1294+ async for byte_content in self.aiter_bytes():1295+ text_content = decoder.decode(byte_content)1296+ for chunk in chunker.decode(text_content):1297+ yield chunk1298+ text_content = decoder.flush()1299+ for chunk in chunker.decode(text_content):1300+ yield chunk1301+ for chunk in chunker.flush():1302+ yield chunk1303 1304 async def aiter_lines(self) -> typing.AsyncIterator[str]:1305 decoder = LineDecoder()1306 with self._wrap_decoder_errors():2 unmodified lines1309 yield line1310 for line in decoder.flush():1311 yield line1312 1272- async def aiter_raw(self) -> typing.AsyncIterator[bytes]:1313+ async def aiter_raw(self, chunk_size: int = None) -> typing.AsyncIterator[bytes]:1314 """1315 A byte-iterator over the raw response content.1316 """1317 if self.is_stream_consumed:4 unmodified lines1322 raise RuntimeError("Attempted to call a async iterator on a sync stream.")1323 1324 self.is_stream_consumed = True1325 self._num_bytes_downloaded = 01326+ chunker = ByteChunker(chunk_size=chunk_size)1327+1328 with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):1286- async for part in self.stream:1287- self._num_bytes_downloaded += len(part)1288- yield part1329+ async for raw_stream_bytes in self.stream:1330+ self._num_bytes_downloaded += len(raw_stream_bytes)1331+ for chunk in chunker.decode(raw_stream_bytes):1332+ yield chunk1333+1334+ for chunk in chunker.flush():1335+ yield chunk1336+1337 await self.aclose()1338 1339 async def aclose(self) -> None:1340 """188 unmodified linesmodified:tests/models/test_responses.py+94 added-4 removed
341 unmodified lines342 raw += part343 assert raw == b"Hello, world!"344 345 346+def test_iter_raw_with_chunksize():347+ response = httpx.Response(200, content=streaming_body())348+349+ parts = [part for part in response.iter_raw(chunk_size=5)]350+ assert parts == [b"Hello", b", wor", b"ld!"]351+352+ response = httpx.Response(200, content=streaming_body())353+354+ parts = [part for part in response.iter_raw(chunk_size=13)]355+ assert parts == [b"Hello, world!"]356+357+ response = httpx.Response(200, content=streaming_body())358+359+ parts = [part for part in response.iter_raw(chunk_size=20)]360+ assert parts == [b"Hello, world!"]361+362+363 def test_iter_raw_on_iterable():364 response = httpx.Response(365 200,366 content=StreamingBody(),34 unmodified lines401 assert raw == b"Hello, world!"402 403 404 @pytest.mark.asyncio405+async def test_aiter_raw_with_chunksize():406+ response = httpx.Response(200, content=async_streaming_body())407+408+ parts = [part async for part in response.aiter_raw(chunk_size=5)]409+ assert parts == [b"Hello", b", wor", b"ld!"]410+411+ response = httpx.Response(200, content=async_streaming_body())412+413+ parts = [part async for part in response.aiter_raw(chunk_size=13)]414+ assert parts == [b"Hello, world!"]415+416+ response = httpx.Response(200, content=async_streaming_body())417+418+ parts = [part async for part in response.aiter_raw(chunk_size=20)]419+ assert parts == [b"Hello, world!"]420+421+422+@pytest.mark.asyncio423 async def test_aiter_raw_on_sync():424 response = httpx.Response(425 200,426 content=streaming_body(),13 unmodified lines440 num_downloaded = response.num_bytes_downloaded441 442 443 def test_iter_bytes():409- response = httpx.Response(410- 200,411- content=b"Hello, world!",412- )444+ response = httpx.Response(200, content=b"Hello, world!")445 446 content = b""447 for part in response.iter_bytes():448 content += part449 assert content == b"Hello, world!"450 451 452+def test_iter_bytes_with_chunk_size():453+ response = httpx.Response(200, content=streaming_body())454+ parts = [part for part in response.iter_bytes(chunk_size=5)]455+ assert parts == [b"Hello", b", wor", b"ld!"]456+457+ response = httpx.Response(200, content=streaming_body())458+ parts = [part for part in response.iter_bytes(chunk_size=13)]459+ assert parts == [b"Hello, world!"]460+461+ response = httpx.Response(200, content=streaming_body())462+ parts = [part for part in response.iter_bytes(chunk_size=20)]463+ assert parts == [b"Hello, world!"]464+465+466 @pytest.mark.asyncio467 async def test_aiter_bytes():468 response = httpx.Response(469 200,5 unmodified lines475 content += part476 assert content == b"Hello, world!"477 478 479+@pytest.mark.asyncio480+async def test_aiter_bytes_with_chunk_size():481+ response = httpx.Response(200, content=async_streaming_body())482+ parts = [part async for part in response.aiter_bytes(chunk_size=5)]483+ assert parts == [b"Hello", b", wor", b"ld!"]484+485+ response = httpx.Response(200, content=async_streaming_body())486+ parts = [part async for part in response.aiter_bytes(chunk_size=13)]487+ assert parts == [b"Hello, world!"]488+489+ response = httpx.Response(200, content=async_streaming_body())490+ parts = [part async for part in response.aiter_bytes(chunk_size=20)]491+ assert parts == [b"Hello, world!"]492+493+494 def test_iter_text():495 response = httpx.Response(496 200,497 content=b"Hello, world!",4 unmodified lines502 content += part503 assert content == "Hello, world!"504 505 506+def test_iter_text_with_chunk_size():507+ response = httpx.Response(200, content=b"Hello, world!")508+ parts = [part for part in response.iter_text(chunk_size=5)]509+ assert parts == ["Hello", ", wor", "ld!"]510+511+ response = httpx.Response(200, content=b"Hello, world!")512+ parts = [part for part in response.iter_text(chunk_size=13)]513+ assert parts == ["Hello, world!"]514+515+ response = httpx.Response(200, content=b"Hello, world!")516+ parts = [part for part in response.iter_text(chunk_size=20)]517+ assert parts == ["Hello, world!"]518+519+520 @pytest.mark.asyncio521 async def test_aiter_text():522 response = httpx.Response(523 200,5 unmodified lines529 content += part530 assert content == "Hello, world!"531 532 533+@pytest.mark.asyncio534+async def test_aiter_text_with_chunk_size():535+ response = httpx.Response(200, content=b"Hello, world!")536+ parts = [part async for part in response.aiter_text(chunk_size=5)]537+ assert parts == ["Hello", ", wor", "ld!"]538+539+ response = httpx.Response(200, content=b"Hello, world!")540+ parts = [part async for part in response.aiter_text(chunk_size=13)]541+ assert parts == ["Hello, world!"]542+543+ response = httpx.Response(200, content=b"Hello, world!")544+ parts = [part async for part in response.aiter_text(chunk_size=20)]545+ assert parts == ["Hello, world!"]546+547+548 def test_iter_lines():549 response = httpx.Response(550 200,551 content=b"Hello,\nworld!",283 unmodified linesmodified:tests/test_decoders.py+46 added
4 unmodified lines5 6 import httpx7 from httpx._decoders import (8 BrotliDecoder,9+ ByteChunker,10 DeflateDecoder,11 GZipDecoder,12 IdentityDecoder,13 LineDecoder,14+ TextChunker,15 TextDecoder,16 )17 18 282 unmodified lines301 assert decoder.decode("baz\r\n") == ["foo bar baz\n"]302 assert decoder.flush() == []303 304 305+def test_byte_chunker():306+ decoder = ByteChunker()307+ assert decoder.decode(b"1234567") == [b"1234567"]308+ assert decoder.decode(b"89") == [b"89"]309+ assert decoder.flush() == []310+311+ decoder = ByteChunker(chunk_size=3)312+ assert decoder.decode(b"1234567") == [b"123", b"456"]313+ assert decoder.decode(b"89") == [b"789"]314+ assert decoder.flush() == []315+316+ decoder = ByteChunker(chunk_size=3)317+ assert decoder.decode(b"123456") == [b"123", b"456"]318+ assert decoder.decode(b"789") == [b"789"]319+ assert decoder.flush() == []320+321+ decoder = ByteChunker(chunk_size=3)322+ assert decoder.decode(b"123456") == [b"123", b"456"]323+ assert decoder.decode(b"78") == []324+ assert decoder.flush() == [b"78"]325+326+327+def test_text_chunker():328+ decoder = TextChunker()329+ assert decoder.decode("1234567") == ["1234567"]330+ assert decoder.decode("89") == ["89"]331+ assert decoder.flush() == []332+333+ decoder = TextChunker(chunk_size=3)334+ assert decoder.decode("1234567") == ["123", "456"]335+ assert decoder.decode("89") == ["789"]336+ assert decoder.flush() == []337+338+ decoder = TextChunker(chunk_size=3)339+ assert decoder.decode("123456") == ["123", "456"]340+ assert decoder.decode("789") == ["789"]341+ assert decoder.flush() == []342+343+ decoder = TextChunker(chunk_size=3)344+ assert decoder.decode("123456") == ["123", "456"]345+ assert decoder.decode("78") == []346+ assert decoder.flush() == ["78"]347+348+349 def test_invalid_content_encoding_header():350 headers = [(b"Content-Encoding", b"invalid-header")]351 body = b"test 123"352 6 unmodified lines