Skip to content
Myr

Fix bytes support in multipart uploads (#974)

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

authored by Florimond Manca · committed by GitHub · parent a58be59 · Browse files · 2 files+13 added−7 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+13 added−7 removed

  • tests:+10 added−4 removed
  • other:+3 added−3 removed

2 files+13 added−7 removed

modified:httpx/_content_streams.py+3 added-3 removed
245 unmodified lines
246247 def get_length(self) -> int:248 headers = self.render_headers()249250 if isinstance(self.file, str):250 if isinstance(self.file, (str, bytes)):251 return len(headers) + len(self.file)252253 # Let's do our best not to read `file` into memory.254 try:
23 unmodified lines
278279 return self._headers280281 def render_data(self) -> typing.Iterator[bytes]:282 if isinstance(self.file, str):282 if isinstance(self.file, (str, bytes)):283 yield to_bytes(self.file)284 return285286 if hasattr(self, "_data"):
9 unmodified lines
296 assert self.file.seekable()297 self.file.seek(0)298299 def can_replay(self) -> bool:300 return True if isinstance(self.file, str) else self.file.seekable()300 return True if isinstance(self.file, (str, bytes)) else self.file.seekable()301302 def render(self) -> typing.Iterator[bytes]:303 yield self.render_headers()304 yield from self.render_data()
96 unmodified lines
modified:tests/test_multipart.py+10 added-4 removed
179 unmodified lines
180 "".encode("ascii")181 )182183184def test_multipart_encode_files_allows_str_content() -> None:185 files = {"file": ("test.txt", "<string content>", "text/plain")}184@pytest.mark.parametrize(185 "value, output",186 ((b"<bytes content>", "<bytes content>"), ("<string content>", "<string content>")),187)188def test_multipart_encode_files_allows_bytes_or_str_content(189 value: typing.Union[str, bytes], output: str190) -> None:191 files = {"file": ("test.txt", value, "text/plain")}192 with mock.patch("os.urandom", return_value=os.urandom(16)):193 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")194195 stream = encode(data={}, files=files)
2 unmodified lines
198 assert stream.content_type == f"multipart/form-data; boundary={boundary}"199 content = (200 '--{0}\r\nContent-Disposition: form-data; name="file"; '201 'filename="test.txt"\r\n'196 "Content-Type: text/plain\r\n\r\n<string content>\r\n"202 "Content-Type: text/plain\r\n\r\n{1}\r\n"203 "--{0}--\r\n"198 "".format(boundary).encode("ascii")204 "".format(boundary, output).encode("ascii")205 )206 assert stream.get_headers()["Content-Length"] == str(len(content))207 assert b"".join(stream) == content208
57 unmodified lines