Skip to content
Myr

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

4 files+293 added−30 removed

modified:httpx/_decoders.py+79 added
2 unmodified lines
34See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding5"""6import codecs7import io8import typing9import zlib1011try:
143 unmodified lines
155 data = child.decode(data) + child.flush()156 return data157158159class ByteChunker:160 """161 Handles returning byte content in fixed-size chunks.162 """163164 def __init__(self, chunk_size: int = None) -> None:165 self._buffer = io.BytesIO()166 self._chunk_size = chunk_size167168 def decode(self, content: bytes) -> typing.List[bytes]:169 if self._chunk_size is None:170 return [content]171172 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 []190191 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 []196197198class TextChunker:199 """200 Handles returning text content in fixed-size chunks.201 """202203 def __init__(self, chunk_size: int = None) -> None:204 self._buffer = io.StringIO()205 self._chunk_size = chunk_size206207 def decode(self, content: str) -> typing.List[str]:208 if self._chunk_size is None:209 return [content]210211 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 []229230 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 []235236237class TextDecoder:238 """239 Handles incrementally decoding bytes into text240 """
127 unmodified lines
modified:httpx/_models.py+74 added-26 removed
13 unmodified lines
1415from ._content import PlainByteStream, encode_request, encode_response16from ._decoders import (17 SUPPORTED_DECODERS,18 ByteChunker,19 ContentDecoder,20 IdentityDecoder,21 LineDecoder,22 MultiDecoder,23 TextChunker,24 TextDecoder,25)26from ._exceptions import (27 HTTPCORE_EXC_MAP,
1135 unmodified lines
1163 if not hasattr(self, "_content"):1164 self._content = b"".join(self.iter_bytes())1165 return self._content11661165 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 chunk11891179 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 chunk12081209 def iter_lines(self) -> typing.Iterator[str]:1210 decoder = LineDecoder()1211 with self._wrap_decoder_errors():
2 unmodified lines
1214 yield line1215 for line in decoder.flush():1216 yield line12171200 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 lines
1227 raise RuntimeError("Attempted to call a sync iterator on an async stream.")12281229 self.is_stream_consumed = True1230 self._num_bytes_downloaded = 01231 chunker = ByteChunker(chunk_size=chunk_size)12321233 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 chunk12381239 for chunk in chunker.flush():1240 yield chunk12411242 self.close()12431244 def close(self) -> None:1245 """
12 unmodified lines
1258 if not hasattr(self, "_content"):1259 self._content = b"".join([part async for part in self.aiter_bytes()])1260 return self._content12611237 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 chunk12841251 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 chunk13031304 async def aiter_lines(self) -> typing.AsyncIterator[str]:1305 decoder = LineDecoder()1306 with self._wrap_decoder_errors():
2 unmodified lines
1309 yield line1310 for line in decoder.flush():1311 yield line13121272 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 lines
1322 raise RuntimeError("Attempted to call a async iterator on a sync stream.")13231324 self.is_stream_consumed = True1325 self._num_bytes_downloaded = 01326 chunker = ByteChunker(chunk_size=chunk_size)13271328 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 chunk13331334 for chunk in chunker.flush():1335 yield chunk13361337 await self.aclose()13381339 async def aclose(self) -> None:1340 """
188 unmodified lines
modified:tests/models/test_responses.py+94 added-4 removed
341 unmodified lines
342 raw += part343 assert raw == b"Hello, world!"344345346def test_iter_raw_with_chunksize():347 response = httpx.Response(200, content=streaming_body())348349 parts = [part for part in response.iter_raw(chunk_size=5)]350 assert parts == [b"Hello", b", wor", b"ld!"]351352 response = httpx.Response(200, content=streaming_body())353354 parts = [part for part in response.iter_raw(chunk_size=13)]355 assert parts == [b"Hello, world!"]356357 response = httpx.Response(200, content=streaming_body())358359 parts = [part for part in response.iter_raw(chunk_size=20)]360 assert parts == [b"Hello, world!"]361362363def test_iter_raw_on_iterable():364 response = httpx.Response(365 200,366 content=StreamingBody(),
34 unmodified lines
401 assert raw == b"Hello, world!"402403404@pytest.mark.asyncio405async def test_aiter_raw_with_chunksize():406 response = httpx.Response(200, content=async_streaming_body())407408 parts = [part async for part in response.aiter_raw(chunk_size=5)]409 assert parts == [b"Hello", b", wor", b"ld!"]410411 response = httpx.Response(200, content=async_streaming_body())412413 parts = [part async for part in response.aiter_raw(chunk_size=13)]414 assert parts == [b"Hello, world!"]415416 response = httpx.Response(200, content=async_streaming_body())417418 parts = [part async for part in response.aiter_raw(chunk_size=20)]419 assert parts == [b"Hello, world!"]420421422@pytest.mark.asyncio423async def test_aiter_raw_on_sync():424 response = httpx.Response(425 200,426 content=streaming_body(),
13 unmodified lines
440 num_downloaded = response.num_bytes_downloaded441442443def test_iter_bytes():409 response = httpx.Response(410 200,411 content=b"Hello, world!",412 )444 response = httpx.Response(200, content=b"Hello, world!")445446 content = b""447 for part in response.iter_bytes():448 content += part449 assert content == b"Hello, world!"450451452def 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!"]456457 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!"]460461 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!"]464465466@pytest.mark.asyncio467async def test_aiter_bytes():468 response = httpx.Response(469 200,
5 unmodified lines
475 content += part476 assert content == b"Hello, world!"477478479@pytest.mark.asyncio480async 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!"]484485 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!"]488489 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!"]492493494def test_iter_text():495 response = httpx.Response(496 200,497 content=b"Hello, world!",
4 unmodified lines
502 content += part503 assert content == "Hello, world!"504505506def 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!"]510511 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!"]514515 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!"]518519520@pytest.mark.asyncio521async def test_aiter_text():522 response = httpx.Response(523 200,
5 unmodified lines
529 content += part530 assert content == "Hello, world!"531532533@pytest.mark.asyncio534async 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!"]538539 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!"]542543 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!"]546547548def test_iter_lines():549 response = httpx.Response(550 200,551 content=b"Hello,\nworld!",
283 unmodified lines
modified:tests/test_decoders.py+46 added
4 unmodified lines
56import httpx7from httpx._decoders import (8 BrotliDecoder,9 ByteChunker,10 DeflateDecoder,11 GZipDecoder,12 IdentityDecoder,13 LineDecoder,14 TextChunker,15 TextDecoder,16)1718
282 unmodified lines
301 assert decoder.decode("baz\r\n") == ["foo bar baz\n"]302 assert decoder.flush() == []303304305def 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() == []310311 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() == []315316 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() == []320321 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"]325326327def test_text_chunker():328 decoder = TextChunker()329 assert decoder.decode("1234567") == ["1234567"]330 assert decoder.decode("89") == ["89"]331 assert decoder.flush() == []332333 decoder = TextChunker(chunk_size=3)334 assert decoder.decode("1234567") == ["123", "456"]335 assert decoder.decode("89") == ["789"]336 assert decoder.flush() == []337338 decoder = TextChunker(chunk_size=3)339 assert decoder.decode("123456") == ["123", "456"]340 assert decoder.decode("789") == ["789"]341 assert decoder.flush() == []342343 decoder = TextChunker(chunk_size=3)344 assert decoder.decode("123456") == ["123", "456"]345 assert decoder.decode("78") == []346 assert decoder.flush() == ["78"]347348349def test_invalid_content_encoding_header():350 headers = [(b"Content-Encoding", b"invalid-header")]351 body = b"test 123"352
6 unmodified lines