Allow str content for multipart upload files (#2400)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by GitHub · parent 770d4f2 · Browse files · 3 files·+33 added−8 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+33 added−8 removed
- tests:+24 added−5 removed
- other:+9 added−3 removed
Provenance
- Commit
0ebe925- Tree
f7841ae- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
770d4f2
3 files changed+33 added−8 removed
modified:httpx/_multipart.py+8 added-2 removed
120 unmodified lines121 # provided in the 3rd tuple element if it is also included in the headers122 # requests does the opposite (it overwrites the header with the 3rd tuple element)123 headers["Content-Type"] = content_type124 125- if isinstance(fileobj, (str, io.StringIO)):126- raise TypeError(f"Expected bytes or bytes-like object got: {type(fileobj)}")125+ if "b" not in getattr(fileobj, "mode", "b"):126+ raise TypeError(127+ "Multipart file uploads must be opened in binary mode, not text mode."128+ )129+ if isinstance(fileobj, io.StringIO):130+ raise TypeError(131+ "Multipart file uploads require 'io.BytesIO', not 'io.StringIO'."132+ )133 134 self.filename = filename135 self.file = fileobj136 self.headers = headers124 unmodified linesmodified:httpx/_types.py+1 added-1 removed
78 unmodified lines79 ResponseExtensions = Dict[str, Any]80 81 RequestData = Mapping[str, Any]82 83-FileContent = Union[IO[bytes], bytes]83+FileContent = Union[IO[bytes], bytes, str]84 FileTypes = Union[85 # file (or bytes)86 FileContent,87 # (filename, file (or bytes))66 unmodified linesmodified:tests/test_multipart.py+24 added-5 removed
337 unmodified lines338 }339 assert content == b"".join(stream)340 341 342-def test_multipart_encode_files_raises_exception_with_str_content() -> None:343- files = {"file": ("test.txt", "<bytes content>", "text/plain")}342+def test_multipart_encode_files_allows_str_content() -> None:343+ files = {"file": ("test.txt", "<str content>", "text/plain")}344 with mock.patch("os.urandom", return_value=os.urandom(16)):345+ boundary = os.urandom(16).hex()346 346- with pytest.raises(TypeError):347- encode_request(data={}, files=files) # type: ignore347+ headers, stream = encode_request(data={}, files=files)348+ assert isinstance(stream, typing.Iterable)349 350+ content = (351+ '--{0}\r\nContent-Disposition: form-data; name="file"; '352+ 'filename="test.txt"\r\n'353+ "Content-Type: text/plain\r\n\r\n<str content>\r\n"354+ "--{0}--\r\n"355+ "".format(boundary).encode("ascii")356+ )357+ assert headers == {358+ "Content-Type": f"multipart/form-data; boundary={boundary}",359+ "Content-Length": str(len(content)),360+ }361+ assert content == b"".join(stream)362 363+364 def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:365 files = {"file": ("test.txt", io.StringIO("content"), "text/plain")}352- with mock.patch("os.urandom", return_value=os.urandom(16)):366+ with pytest.raises(TypeError):367+ encode_request(data={}, files=files) # type: ignore368 369+370+def test_multipart_encode_files_raises_exception_with_text_mode_file() -> None:371+ with tempfile.TemporaryFile(mode="w") as upload:372+ files = {"file": ("test.txt", upload, "text/plain")}373 with pytest.raises(TypeError):374 encode_request(data={}, files=files) # type: ignore375 376 72 unmodified lines