Implement streaming multipart uploads (#857)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Implement streaming multipart uploads * Tweak seekable check * Don't handle duplicate computation yet * Add memory test for multipart streaming * Lint * 1 pct is enough * Tweak lazy computations, fallback to non-streaming for broken filelikes * Reduce diff size * Drop memory test * Cleanup
authored by Florimond Manca · committed by GitHub · parent af75908 · Browse files · 3 files·+224 added−67 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+224 added−67 removed
- tests:+64 added−10 removed
- other:+160 added−57 removed
Provenance
- Commit
5829ecb- Tree
afc7c50- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
af75908
3 files changed+224 added−67 removed
modified:httpx/_content_streams.py+127 added-57 removed
1 import binascii2-import mimetypes2 import os3 import typing5-from io import BytesIO4 from json import dumps as json_dumps5 from pathlib import Path6 from urllib.parse import urlencode7 8 import httpcore9 10 from ._exceptions import StreamConsumed11 from ._types import StrOrBytes14-from ._utils import format_form_param12+from ._utils import (13+ format_form_param,14+ guess_content_type,15+ peek_filelike_length,16+ to_bytes,17+)18 19 RequestData = typing.Union[20 dict, str, bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]21 ]175 unmodified lines197 198 199 class MultipartStream(ContentStream):200 """198- Request content as multipart encoded form data.201+ Request content as streaming multipart encoded form data.202 """203 204 class DataField:205 """8 unmodified lines214 self.name = name215 self.value = value216 217 def render_headers(self) -> bytes:215- name = format_form_param("name", self.name)216- return b"".join([b"Content-Disposition: form-data; ", name, b"\r\n\r\n"])218+ if not hasattr(self, "_headers"):219+ name = format_form_param("name", self.name)220+ self._headers = b"".join(221+ [b"Content-Disposition: form-data; ", name, b"\r\n\r\n"]222+ )223 224+ return self._headers225+226 def render_data(self) -> bytes:227+ if not hasattr(self, "_data"):219- return (220- self.value221- if isinstance(self.value, bytes)222- else self.value.encode("utf-8")223- )228+ self._data = (229+ self.value230+ if isinstance(self.value, bytes)231+ else self.value.encode("utf-8")232+ )233 234+ return self._data235+236+ def get_length(self) -> int:237+ headers = self.render_headers()238+ data = self.render_data()239+ return len(headers) + len(data)240+241+ def can_replay(self) -> bool:242+ return True243+244+ def render(self) -> typing.Iterator[bytes]:245+ yield self.render_headers()246+ yield self.render_data()247+248 class FileField:249 """250 A single file field item, within a multipart form field.251 """5 unmodified lines257 ) -> None:258 self.name = name259 if not isinstance(value, tuple):260 self.filename = Path(str(getattr(value, "name", "upload"))).name238- self.file = (239- value240- ) # type: typing.Union[typing.IO[str], typing.IO[bytes]]241- self.content_type = self.guess_content_type()261+ self.file: typing.Union[typing.IO[str], typing.IO[bytes]] = value262+ self.content_type = guess_content_type(self.filename)263 else:264 self.filename = value[0]265 self.file = value[1]266 self.content_type = (246- value[2] if len(value) > 2 else self.guess_content_type()267+ value[2] if len(value) > 2 else guess_content_type(self.filename)268 )269 249- def guess_content_type(self) -> typing.Optional[str]:250- if self.filename:251- return (252- mimetypes.guess_type(self.filename)[0] or "application/octet-stream"253- )254- else:255- return None270+ def get_length(self) -> int:271+ headers = self.render_headers()272 273+ if isinstance(self.file, str):274+ return len(headers) + len(self.file)275+276+ # Let's do our best not to read `file` into memory.277+ try:278+ file_length = peek_filelike_length(self.file)279+ except OSError:280+ # As a last resort, read file and cache contents for later.281+ assert not hasattr(self, "_data")282+ self._data = to_bytes(self.file.read())283+ file_length = len(self._data)284+285+ return len(headers) + file_length286+287 def render_headers(self) -> bytes:288+ if not hasattr(self, "_headers"):258- parts = [259- b"Content-Disposition: form-data; ",260- format_form_param("name", self.name),261- ]262- if self.filename:263- filename = format_form_param("filename", self.filename)264- parts.extend([b"; ", filename])265- if self.content_type is not None:266- content_type = self.content_type.encode()267- parts.extend([b"\r\nContent-Type: ", content_type])268- parts.append(b"\r\n\r\n")269- return b"".join(parts)289+ parts = [290+ b"Content-Disposition: form-data; ",291+ format_form_param("name", self.name),292+ ]293+ if self.filename:294+ filename = format_form_param("filename", self.filename)295+ parts.extend([b"; ", filename])296+ if self.content_type is not None:297+ content_type = self.content_type.encode()298+ parts.extend([b"\r\nContent-Type: ", content_type])299+ parts.append(b"\r\n\r\n")300+ self._headers = b"".join(parts)301 271- def render_data(self) -> bytes:272- content: typing.Union[str, bytes]302+ return self._headers303+304+ def render_data(self) -> typing.Iterator[bytes]:305 if isinstance(self.file, str):274- content = self.file275- else:276- content = self.file.read()277- return content.encode("utf-8") if isinstance(content, str) else content306+ yield to_bytes(self.file)307+ return308 279- def __init__(self, data: dict, files: dict, boundary: bytes = None) -> None:280- body = BytesIO()281- if boundary is None:282- boundary = binascii.hexlify(os.urandom(16))309+ if hasattr(self, "_data"):310+ # Already rendered.311+ yield self._data312+ return313 284- for field in self.iter_fields(data, files):285- body.write(b"--%s\r\n" % boundary)286- body.write(field.render_headers())287- body.write(field.render_data())288- body.write(b"\r\n")314+ for chunk in self.file:315+ yield to_bytes(chunk)316 290- body.write(b"--%s--\r\n" % boundary)317+ # Get ready for the next replay, if possible.318+ if self.can_replay():319+ assert self.file.seekable()320+ self.file.seek(0)321 322+ def can_replay(self) -> bool:323+ return True if isinstance(self.file, str) else self.file.seekable()324+325+ def render(self) -> typing.Iterator[bytes]:326+ yield self.render_headers()327+ yield from self.render_data()328+329+ def __init__(330+ self, data: typing.Mapping, files: typing.Mapping, boundary: bytes = None331+ ) -> None:332+ if boundary is None:333+ boundary = binascii.hexlify(os.urandom(16))334+335+ self.boundary = boundary336 self.content_type = "multipart/form-data; boundary=%s" % boundary.decode(337 "ascii"338 )295- self.body = body.getvalue()339+ self.fields = list(self._iter_fields(data, files))340 297- def iter_fields(298- self, data: dict, files: dict341+ def _iter_fields(342+ self, data: typing.Mapping, files: typing.Mapping343 ) -> typing.Iterator[typing.Union["FileField", "DataField"]]:344 for name, value in data.items():345 if isinstance(value, list):346 for item in value:3 unmodified lines350 351 for name, value in files.items():352 yield self.FileField(name=name, value=value)353 354+ def iter_chunks(self) -> typing.Iterator[bytes]:355+ for field in self.fields:356+ yield b"--%s\r\n" % self.boundary357+ yield from field.render()358+ yield b"\r\n"359+ yield b"--%s--\r\n" % self.boundary360+361+ def iter_chunks_lengths(self) -> typing.Iterator[int]:362+ boundary_length = len(self.boundary)363+ # Follow closely what `.iter_chunks()` does.364+ for field in self.fields:365+ yield 2 + boundary_length + 2366+ yield field.get_length()367+ yield 2368+ yield 2 + boundary_length + 4369+370+ def get_content_length(self) -> int:371+ return sum(self.iter_chunks_lengths())372+373+ # Content stream interface.374+375+ def can_replay(self) -> bool:376+ return all(field.can_replay() for field in self.fields)377+378 def get_headers(self) -> typing.Dict[str, str]:311- content_length = str(len(self.body))379+ content_length = str(self.get_content_length())380 content_type = self.content_type381 return {"Content-Length": content_length, "Content-Type": content_type}382 383 def __iter__(self) -> typing.Iterator[bytes]:316- yield self.body384+ for chunk in self.iter_chunks():385+ yield chunk386 387 async def __aiter__(self) -> typing.AsyncIterator[bytes]:319- yield self.body388+ for chunk in self.iter_chunks():389+ yield chunk390 391 392 def encode(393 data: RequestData = None,30 unmodified linesmodified:httpx/_utils.py+33 added
1 import codecs2 import collections3 import contextlib4 import logging5+import mimetypes6 import netrc7 import os8 import re9 import sys300 unmodified lines310 def unquote(value: str) -> str:311 return value[1:-1] if value[0] == value[-1] == '"' else value312 313 314+def guess_content_type(filename: typing.Optional[str]) -> typing.Optional[str]:315+ if filename:316+ return mimetypes.guess_type(filename)[0] or "application/octet-stream"317+ return None318+319+320+def peek_filelike_length(stream: typing.IO) -> int:321+ """322+ Given a file-like stream object, return its length in number of bytes323+ without reading it into memory.324+ """325+ try:326+ # Is it an actual file?327+ fd = stream.fileno()328+ except OSError:329+ # No... Maybe it's something that supports random access, like `io.BytesIO`?330+ try:331+ # Assuming so, go to end of stream to figure out its length,332+ # then put it back in place.333+ offset = stream.tell()334+ length = stream.seek(0, os.SEEK_END)335+ stream.seek(offset)336+ except OSError:337+ # Not even that? Sorry, we're doomed...338+ raise339+ else:340+ return length341+ else:342+ # Yup, seems to be an actual file.343+ return os.fstat(fd).st_size344+345+346 def flatten_queryparams(347 queryparams: typing.Mapping[348 str, typing.Union["PrimitiveData", typing.Sequence["PrimitiveData"]]349 ]54 unmodified linesmodified:tests/test_multipart.py+64 added-10 removed
99 unmodified lines100 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]101 assert multipart["file"] == [b"<file content>"]102 103 104-def test_multipart_encode():104+def test_multipart_encode(tmp_path: typing.Any) -> None:105+ path = str(tmp_path / "name.txt")106+ with open(path, "wb") as f:107+ f.write(b"<file content>")108+109 data = {110 "a": "1",111 "b": b"C",112 "c": ["11", "22", "33"],113 "d": "",114 }111- files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}115+ files = {"file": ("name.txt", open(path, "rb"))}116 117 with mock.patch("os.urandom", return_value=os.urandom(16)):118 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")119+120 stream = encode(data=data, files=files)121+ assert stream.can_replay()122+123 assert stream.content_type == f"multipart/form-data; boundary={boundary}"117- assert stream.body == (124+ content = (125 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'126 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'127 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'128 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'4 unmodified lines133 "Content-Type: text/plain\r\n\r\n<file content>\r\n"134 "--{0}--\r\n"135 "".format(boundary).encode("ascii")136 )137+ assert stream.get_headers()["Content-Length"] == str(len(content))138+ assert b"".join(stream) == content139 140 132-def test_multipart_encode_files_allows_filenames_as_none():141+def test_multipart_encode_files_allows_filenames_as_none() -> None:142 files = {"file": (None, io.BytesIO(b"<file content>"))}143 with mock.patch("os.urandom", return_value=os.urandom(16)):144 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")145 146 stream = encode(data={}, files=files)147+ assert stream.can_replay()148 149 assert stream.content_type == f"multipart/form-data; boundary={boundary}"140- assert stream.body == (150+ assert b"".join(stream) == (151 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'152 "<file content>\r\n--{0}--\r\n"153 "".format(boundary).encode("ascii")154 )7 unmodified lines162 ("no-extension", "application/octet-stream"),163 ],164 )165 def test_multipart_encode_files_guesses_correct_content_type(156- file_name, expected_content_type157-):166+ file_name: str, expected_content_type: str167+) -> None:168 files = {"file": (file_name, io.BytesIO(b"<file content>"))}169 with mock.patch("os.urandom", return_value=os.urandom(16)):170 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")171 172 stream = encode(data={}, files=files)173+ assert stream.can_replay()174 175 assert stream.content_type == f"multipart/form-data; boundary={boundary}"165- assert stream.body == (176+ assert b"".join(stream) == (177 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '178 f'filename="{file_name}"\r\nContent-Type: '179 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"180 "".encode("ascii")181 )182 183 173-def test_multipart_encode_files_allows_str_content():184+def test_multipart_encode_files_allows_str_content() -> None:185 files = {"file": ("test.txt", "<string content>", "text/plain")}186 with mock.patch("os.urandom", return_value=os.urandom(16)):187 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")188 189 stream = encode(data={}, files=files)190+ assert stream.can_replay()191 192 assert stream.content_type == f"multipart/form-data; boundary={boundary}"181- assert stream.body == (193+ content = (194 '--{0}\r\nContent-Disposition: form-data; name="file"; '195 'filename="test.txt"\r\n'196 "Content-Type: text/plain\r\n\r\n<string content>\r\n"197 "--{0}--\r\n"198 "".format(boundary).encode("ascii")199 )200+ assert stream.get_headers()["Content-Length"] == str(len(content))201+ assert b"".join(stream) == content202 203 204+def test_multipart_encode_non_seekable_filelike() -> None:205+ """206+ Test that special readable but non-seekable filelike objects are supported,207+ at the cost of reading them into memory at most once.208+ """209+210+ class IteratorIO(io.IOBase):211+ def __init__(self, iterator: typing.Iterator[bytes]) -> None:212+ self._iterator = iterator213+214+ def seekable(self) -> bool:215+ return False216+217+ def read(self, *args: typing.Any) -> bytes:218+ return b"".join(self._iterator)219+220+ def data() -> typing.Iterator[bytes]:221+ yield b"Hello"222+ yield b"World"223+224+ fileobj = IteratorIO(data())225+ files = {"file": fileobj}226+ stream = encode(files=files, boundary=b"+++")227+ assert not stream.can_replay()228+229+ content = (230+ b"--+++\r\n"231+ b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'232+ b"Content-Type: application/octet-stream\r\n"233+ b"\r\n"234+ b"HelloWorld\r\n"235+ b"--+++--\r\n"236+ )237+ assert stream.get_headers() == {238+ "Content-Type": "multipart/form-data; boundary=+++",239+ "Content-Length": str(len(content)),240+ }241+ assert b"".join(stream) == content242+243+244 class TestHeaderParamHTML5Formatting:245 def test_unicode(self):246 param = format_form_param("filename", "n\u00e4me")247 assert param == b'filename="n\xc3\xa4me"'12 unmodified lines