Skip to content
Myr

Streaming multipart support (#2382)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Streaming multipart support * Update tests for streaming multipary

authored by Tom Christie · committed by GitHub · parent af56476 · Browse files · 2 files+33 added−25 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+33 added−25 removed

  • tests:+4 added−3 removed
  • other:+29 added−22 removed

2 files+33 added−25 removed

modified:httpx/_multipart.py+29 added-22 removed
133 unmodified lines
134 self.filename = filename135 self.file = fileobj136 self.headers = headers137138 def get_length(self) -> int:138 def get_length(self) -> typing.Optional[int]:139 headers = self.render_headers()140141 if isinstance(self.file, (str, bytes)):142 return len(headers) + len(to_bytes(self.file))143144 # Let's do our best not to read `file` into memory.144 file_length = peek_filelike_length(self.file)145146 # If we can't determine the filesize without reading it into memory,147 # then return `None` here, to indicate an unknown file length.148 if file_length is None:147 # As a last resort, read file and cache contents for later.148 assert not hasattr(self, "_data")149 self._data = to_bytes(self.file.read())150 file_length = len(self._data)149 return None150151 return len(headers) + file_length152153 def render_headers(self) -> bytes:
17 unmodified lines
171 if isinstance(self.file, (str, bytes)):172 yield to_bytes(self.file)173 return174176 if hasattr(self, "_data"):177 # Already rendered.178 yield self._data179 return180175 if hasattr(self.file, "seek"):176 try:182 self.file.seek(0)177 self.file.seek(0)178 except io.UnsupportedOperation:179 pass180181 chunk = self.file.read(self.CHUNK_SIZE)182 while chunk:183 yield to_bytes(chunk)
44 unmodified lines
228 yield from field.render()229 yield b"\r\n"230 yield b"--%s--\r\n" % self.boundary231235 def iter_chunks_lengths(self) -> typing.Iterator[int]:232 def get_content_length(self) -> typing.Optional[int]:233 """234 Return the length of the multipart encoded content, or `None` if235 any of the files have a length that cannot be determined upfront.236 """237 boundary_length = len(self.boundary)237 # Follow closely what `.iter_chunks()` does.238 length = 0239240 for field in self.fields:239 yield 2 + boundary_length + 2240 yield field.get_length()241 yield 2242 yield 2 + boundary_length + 4241 field_length = field.get_length()242 if field_length is None:243 return None244244 def get_content_length(self) -> int:245 return sum(self.iter_chunks_lengths())245 length += 2 + boundary_length + 2 # b"--{boundary}\r\n"246 length += field_length247 length += 2 # b"\r\n"248249 length += 2 + boundary_length + 4 # b"--{boundary}--\r\n"250 return length251252 # Content stream interface.253254 def get_headers(self) -> typing.Dict[str, str]:250 content_length = str(self.get_content_length())255 content_length = self.get_content_length()256 content_type = self.content_type257 if content_length is None:258 return {"Transfer-Encoding": "chunked", "Content-Type": content_type}252 return {"Content-Length": content_length, "Content-Type": content_type}259 return {"Content-Length": str(content_length), "Content-Type": content_type}260261 def __iter__(self) -> typing.Iterator[bytes]:262 for chunk in self.iter_chunks():263 yield chunk
4 unmodified lines
modified:tests/test_multipart.py+4 added-3 removed
378 unmodified lines
379380381def test_multipart_encode_non_seekable_filelike() -> None:382 """383 Test that special readable but non-seekable filelike objects are supported,384 at the cost of reading them into memory at most once.383 Test that special readable but non-seekable filelike objects are supported.384 In this case uploads with use 'Transfer-Encoding: chunked', instead of385 a 'Content-Length' header.386 """387388 class IteratorIO(io.IOBase):389 def __init__(self, iterator: typing.Iterator[bytes]) -> None:
20 unmodified lines
410 b"--+++--\r\n"411 )412 assert headers == {413 "Content-Type": "multipart/form-data; boundary=+++",413 "Content-Length": str(len(content)),414 "Transfer-Encoding": "chunked",415 }416 assert content == b"".join(stream)417418
35 unmodified lines