Skip to content
Myr

Allow custom headers in multipart/form-data requests (#1936)

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

* feat: allow passing multipart headers * Add test for including content-type in headers * lint * override content_type with headers * compare tuples based on length * incorporate suggestion * remove .title() on headers

authored by Adrian Garcia Badaracco · committed by GitHub · parent 3eaf69a · Browse files · 3 files+80 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+80 added−8 removed

  • tests:+52 added−0 removed
  • other:+28 added−8 removed

3 files+80 added−8 removed

modified:httpx/_multipart.py+26 added-8 removed
76 unmodified lines
77 self.name = name7879 fileobj: FileContent8081 headers: typing.Dict[str, str] = {}82 content_type: typing.Optional[str] = None8384 # This large tuple based API largely mirror's requests' API85 # It would be good to think of better APIs for this that we could include in httpx 2.086 # since variable length tuples (especially of 4 elements) are quite unwieldly87 if isinstance(value, tuple):82 try:83 filename, fileobj, content_type = value # type: ignore84 except ValueError:88 if len(value) == 2:89 # neither the 3rd parameter (content_type) nor the 4th (headers) was included90 filename, fileobj = value # type: ignore86 content_type = guess_content_type(filename)91 elif len(value) == 3:92 filename, fileobj, content_type = value # type: ignore93 else:94 # all 4 parameters included95 filename, fileobj, content_type, headers = value # type: ignore96 else:97 filename = Path(str(getattr(value, "name", "upload"))).name98 fileobj = value99100 if content_type is None:101 content_type = guess_content_type(filename)102103 has_content_type_header = any("content-type" in key.lower() for key in headers)104 if content_type is not None and not has_content_type_header:105 # note that unlike requests, we ignore the content_type106 # provided in the 3rd tuple element if it is also included in the headers107 # requests does the opposite (it overwrites the header with the 3rd tuple element)108 headers["Content-Type"] = content_type109110 if isinstance(fileobj, (str, io.StringIO)):111 raise TypeError(f"Expected bytes or bytes-like object got: {type(fileobj)}")112113 self.filename = filename114 self.file = fileobj97 self.content_type = content_type115 self.headers = headers116 self._consumed = False117118 def get_length(self) -> int:119 headers = self.render_headers()
19 unmodified lines
139 ]140 if self.filename:141 filename = format_form_param("filename", self.filename)142 parts.extend([b"; ", filename])125 if self.content_type is not None:126 content_type = self.content_type.encode()127 parts.extend([b"\r\nContent-Type: ", content_type])143 for header_name, header_value in self.headers.items():144 key, val = f"\r\n{header_name}: ".encode(), header_value.encode()145 parts.extend([key, val])146 parts.append(b"\r\n\r\n")147 self._headers = b"".join(parts)148149 return self._headers
87 unmodified lines
modified:httpx/_types.py+2 added
87 unmodified lines
88 # (filename, file (or bytes))89 Tuple[Optional[str], FileContent],90 # (filename, file (or bytes), content_type)91 Tuple[Optional[str], FileContent, Optional[str]],92 # (filename, file (or bytes), content_type, headers)93 Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]],94]95RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]9697
55 unmodified lines
modified:tests/test_multipart.py+52 added
92 unmodified lines
93 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]94 assert multipart["file"] == [b"<file content>"]959697@pytest.mark.parametrize("content_type", [None, "text/plain"])98def test_multipart_file_tuple_headers(content_type: typing.Optional[str]):99 file_name = "test.txt"100 expected_content_type = "text/plain"101 headers = {"Expires": "0"}102103 files = {"file": (file_name, io.BytesIO(b"<file content>"), content_type, headers)}104 with mock.patch("os.urandom", return_value=os.urandom(16)):105 boundary = os.urandom(16).hex()106107 headers, stream = encode_request(data={}, files=files)108 assert isinstance(stream, typing.Iterable)109110 content = (111 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '112 f'filename="{file_name}"\r\nExpires: 0\r\nContent-Type: '113 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"114 "".encode("ascii")115 )116 assert headers == {117 "Content-Type": f"multipart/form-data; boundary={boundary}",118 "Content-Length": str(len(content)),119 }120 assert content == b"".join(stream)121122123def test_multipart_headers_include_content_type() -> None:124 """Content-Type from 4th tuple parameter (headers) should override the 3rd parameter (content_type)"""125 file_name = "test.txt"126 expected_content_type = "image/png"127 headers = {"Content-Type": "image/png"}128129 files = {"file": (file_name, io.BytesIO(b"<file content>"), "text_plain", headers)}130 with mock.patch("os.urandom", return_value=os.urandom(16)):131 boundary = os.urandom(16).hex()132133 headers, stream = encode_request(data={}, files=files)134 assert isinstance(stream, typing.Iterable)135136 content = (137 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '138 f'filename="{file_name}"\r\nContent-Type: '139 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"140 "".encode("ascii")141 )142 assert headers == {143 "Content-Type": f"multipart/form-data; boundary={boundary}",144 "Content-Length": str(len(content)),145 }146 assert content == b"".join(stream)147148149def test_multipart_encode(tmp_path: typing.Any) -> None:150 path = str(tmp_path / "name.txt")151 with open(path, "wb") as f:152 f.write(b"<file content>")
205 unmodified lines