Files without a filename should not set a Content-Type in multipart data. (#520)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* File upoads with no filename should not set a Content-Type in their multipart data. * Update type annotations to allow file uploads to be a string
authored by Mattwmaster58 · committed by Tom Christie · parent 7d45db0 · Browse files · 3 files·+41 added−11 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+41 added−11 removed
- tests:+24 added−3 removed
- other:+17 added−8 removed
Provenance
- Commit
ed94950- Tree
df3fc76- Author
Mattwmaster58 <mattmarcus58@gmail.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
7d45db0
3 files changed+41 added−11 removed
modified:httpx/models.py+11 added-4 removed
79 unmodified lines80 81 RequestFiles = typing.Dict[82 str,83 typing.Union[84- typing.IO[typing.AnyStr], # file85- typing.Tuple[str, typing.IO[typing.AnyStr]], # (filename, file)84+ # file (or str)85+ typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],86+ # (filename, file (or str))87 typing.Tuple[87- str, typing.IO[typing.AnyStr], str88- ], # (filename, file, content_type)88+ typing.Optional[str], typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],89+ ],90+ # (filename, file (or str), content_type)91+ typing.Tuple[92+ typing.Optional[str],93+ typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],94+ typing.Optional[str],95+ ],96 ],97 ]98 99 ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]1065 unmodified linesmodified:httpx/multipart.py+6 added-4 removed
56 unmodified lines57 self.content_type = (58 value[2] if len(value) > 2 else self.guess_content_type()59 )60 61- def guess_content_type(self) -> str:61+ def guess_content_type(self) -> typing.Optional[str]:62 if self.filename:63 return mimetypes.guess_type(self.filename)[0] or "application/octet-stream"64 else:65- return "application/octet-stream"65+ return None66 67 def render_headers(self) -> bytes:68 parts = [b"Content-Disposition: form-data; ", _format_param("name", self.name)]69 if self.filename:70 filename = _format_param("filename", self.filename)71 parts.extend([b"; ", filename])72+ if self.content_type is not None:72- content_type = self.content_type.encode()73- parts.extend([b"\r\nContent-Type: ", content_type, b"\r\n\r\n"])73+ content_type = self.content_type.encode()74+ parts.extend([b"\r\nContent-Type: ", content_type])75+ parts.append(b"\r\n\r\n")76 return b"".join(parts)77 78 def render_data(self) -> bytes:79 if isinstance(self.file, str):44 unmodified linesmodified:tests/test_multipart.py+24 added-3 removed
139 unmodified lines140 body, content_type = multipart.multipart_encode(data={}, files=files)141 142 assert content_type == f"multipart/form-data; boundary={boundary}"143 assert body == (144- '--{0}\r\nContent-Disposition: form-data; name="file"\r\n'145- "Content-Type: application/octet-stream\r\n\r\n<file content>\r\n"146- "--{0}--\r\n"144+ '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'145+ "<file content>\r\n--{0}--\r\n"146 "".format(boundary).encode("ascii")147 )148 149 150+@pytest.mark.parametrize(151+ "file_name,expected_content_type",152+ [("example.json", "application/json"), ("example.log", "application/octet-stream")],153+)154+def test_multipart_encode_files_guesses_correct_content_type(155+ file_name, expected_content_type156+):157+ files = {"file": (file_name, io.BytesIO(b"<file content>"))}158+ with mock.patch("os.urandom", return_value=os.urandom(16)):159+ boundary = binascii.hexlify(os.urandom(16)).decode("ascii")160+161+ body, content_type = multipart.multipart_encode(data={}, files=files)162+163+ assert content_type == f"multipart/form-data; boundary={boundary}"164+ assert body == (165+ f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '166+ f'filename="{file_name}"\r\nContent-Type: '167+ f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"168+ "".encode("ascii")169+ )170+171+172 def test_multipart_encode_files_allows_str_content():173 files = {"file": ("test.txt", "<string content>", "text/plain")}174 with mock.patch("os.urandom", return_value=os.urandom(16)):175 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")29 unmodified lines