Read upload files using `read(CHUNK_SIZE)` rather than `iter()`. (#1948)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Cap upload chunk sizes * Use '.read' for file streaming, where possible * Direct iteration should not apply chunk sizes
authored by Tom Christie · committed by GitHub · parent e232226 · Browse files · 3 files·+54 added−5 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+54 added−5 removed
- tests:+25 added−0 removed
- other:+29 added−5 removed
Provenance
- Commit
6f5865f- Tree
d301940- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
e232226
3 files changed+54 added−5 removed
modified:httpx/_content.py+24 added-4 removed
36 unmodified lines37 yield self._stream38 39 40 class IteratorByteStream(SyncByteStream):41+ CHUNK_SIZE = 65_53642+43 def __init__(self, stream: Iterable[bytes]):44 self._stream = stream45 self._is_stream_consumed = False46 self._is_generator = inspect.isgenerator(stream)2 unmodified lines49 if self._is_stream_consumed and self._is_generator:50 raise StreamConsumed()51 52 self._is_stream_consumed = True53+ if hasattr(self._stream, "read"):54+ # File-like interfaces should use 'read' directly.55+ chunk = self._stream.read(self.CHUNK_SIZE) # type: ignore56+ while chunk:57+ yield chunk58+ chunk = self._stream.read(self.CHUNK_SIZE) # type: ignore59+ else:60+ # Otherwise iterate.51- for part in self._stream:52- yield part61+ for part in self._stream:62+ yield part63 64 65 class AsyncIteratorByteStream(AsyncByteStream):66+ CHUNK_SIZE = 65_53667+68 def __init__(self, stream: AsyncIterable[bytes]):69 self._stream = stream70 self._is_stream_consumed = False71 self._is_generator = inspect.isasyncgen(stream)2 unmodified lines74 if self._is_stream_consumed and self._is_generator:75 raise StreamConsumed()76 77 self._is_stream_consumed = True78+ if hasattr(self._stream, "aread"):79+ # File-like interfaces should use 'aread' directly.80+ chunk = await self._stream.aread(self.CHUNK_SIZE) # type: ignore81+ while chunk:82+ yield chunk83+ chunk = await self._stream.aread(self.CHUNK_SIZE) # type: ignore84+ else:85+ # Otherwise iterate.66- async for part in self._stream:67- yield part86+ async for part in self._stream:87+ yield part88 89 90 class UnattachedStream(AsyncByteStream, SyncByteStream):91 """142 unmodified linesmodified:httpx/_multipart.py+5 added-1 removed
69 unmodified lines70 """71 A single file field item, within a multipart form field.72 """73 74+ CHUNK_SIZE = 64 * 102475+76 def __init__(self, name: str, value: FileTypes) -> None:77 self.name = name78 79 fileobj: FileContent63 unmodified lines143 if self._consumed: # pragma: nocover144 self.file.seek(0)145 self._consumed = True146 145- for chunk in self.file:147+ chunk = self.file.read(self.CHUNK_SIZE)148+ while chunk:149 yield to_bytes(chunk)150+ chunk = self.file.read(self.CHUNK_SIZE)151 152 def render(self) -> typing.Iterator[bytes]:153 yield self.render_headers()154 yield from self.render_data()64 unmodified linesmodified:tests/test_content.py+25 added
59 unmodified lines60 assert content == b"Hello, world!"61 62 63 @pytest.mark.asyncio64+async def test_async_bytesio_content():65+ class AsyncBytesIO:66+ def __init__(self, content):67+ self._idx = 068+ self._content = content69+70+ async def aread(self, chunk_size: int):71+ chunk = self._content[self._idx : self._idx + chunk_size]72+ self._idx = self._idx + chunk_size73+ return chunk74+75+ async def __aiter__(self):76+ yield self._content # pragma: nocover77+78+ headers, stream = encode_request(content=AsyncBytesIO(b"Hello, world!"))79+ assert not isinstance(stream, typing.Iterable)80+ assert isinstance(stream, typing.AsyncIterable)81+82+ content = b"".join([part async for part in stream])83+84+ assert headers == {"Transfer-Encoding": "chunked"}85+ assert content == b"Hello, world!"86+87+88+@pytest.mark.asyncio89 async def test_iterator_content():90 def hello_world():91 yield b"Hello, "92 yield b"world!"358 unmodified lines