allow setting an explicit multipart boundary via headers (#2278)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Adrian Garcia Badaracco · committed by GitHub · parent 2434e65 · Browse files · 4 files·+80 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+80 added−2 removed
- tests:+52 added−0 removed
- other:+28 added−2 removed
Provenance
- Commit
1526048- Tree
a9ecd4c- Author
Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
2434e65
4 files changed+80 added−2 removed
modified:httpx/_content.py+1 added-1 removed
148 unmodified lines149 return headers, ByteStream(body)150 151 152 def encode_multipart_data(153- data: dict, files: RequestFiles, boundary: Optional[bytes] = None153+ data: dict, files: RequestFiles, boundary: Optional[bytes]154 ) -> Tuple[Dict[str, str], MultipartStream]:155 multipart = MultipartStream(data=data, files=files, boundary=boundary)156 headers = multipart.get_headers()157 return headers, multipart81 unmodified linesmodified:httpx/_models.py+13 added-1 removed
25 unmodified lines26 StreamClosed,27 StreamConsumed,28 request_context,29 )30+from ._multipart import get_multipart_boundary_from_content_type31 from ._status_codes import codes32 from ._types import (33 AsyncByteStream,34 CookieTypes,297 unmodified lines332 if cookies:333 Cookies(cookies).set_cookie_header(self)334 335 if stream is None:336+ content_type: typing.Optional[str] = self.headers.get("content-type")335- headers, stream = encode_request(content, data, files, json)337+ headers, stream = encode_request(338+ content=content,339+ data=data,340+ files=files,341+ json=json,342+ boundary=get_multipart_boundary_from_content_type(343+ content_type=content_type.encode(self.headers.encoding)344+ if content_type345+ else None346+ ),347+ )348 self._prepare(headers)349 self.stream = stream350 # Load the request body, except for streaming content.351 if isinstance(stream, ByteStream):856 unmodified linesmodified:httpx/_multipart.py+14 added
18 unmodified lines19 to_bytes,20 )21 22 23+def get_multipart_boundary_from_content_type(24+ content_type: typing.Optional[bytes],25+) -> typing.Optional[bytes]:26+ if not content_type or not content_type.startswith(b"multipart/form-data"):27+ return None28+ # parse boundary according to29+ # https://www.rfc-editor.org/rfc/rfc2046#section-5.1.130+ if b";" in content_type:31+ for section in content_type.split(b";"):32+ if section.strip().lower().startswith(b"boundary="):33+ return section.strip()[len(b"boundary=") :].strip(b'"')34+ return None35+36+37 class DataField:38 """39 A single form field item, within a multipart form field.40 """210 unmodified linesmodified:tests/test_multipart.py+52 added
40 unmodified lines41 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]42 assert multipart["file"] == [b"<file content>"]43 44 45+@pytest.mark.parametrize(46+ "header",47+ [48+ "multipart/form-data; boundary=+++; charset=utf-8",49+ "multipart/form-data; charset=utf-8; boundary=+++",50+ "multipart/form-data; boundary=+++",51+ "multipart/form-data; boundary=+++ ;",52+ 'multipart/form-data; boundary="+++"; charset=utf-8',53+ 'multipart/form-data; charset=utf-8; boundary="+++"',54+ 'multipart/form-data; boundary="+++"',55+ 'multipart/form-data; boundary="+++" ;',56+ ],57+)58+def test_multipart_explicit_boundary(header: str) -> None:59+ client = httpx.Client(transport=httpx.MockTransport(echo_request_content))60+61+ files = {"file": io.BytesIO(b"<file content>")}62+ headers = {"content-type": header}63+ response = client.post("http://127.0.0.1:8000/", files=files, headers=headers)64+ assert response.status_code == 20065+66+ # We're using the cgi module to verify the behavior here, which is a67+ # bit grungy, but sufficient just for our testing purposes.68+ assert response.request.headers["Content-Type"] == header69+ content_length = response.request.headers["Content-Length"]70+ pdict: dict = {71+ "boundary": b"+++",72+ "CONTENT-LENGTH": content_length,73+ }74+ multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)75+76+ assert multipart["file"] == [b"<file content>"]77+78+79+@pytest.mark.parametrize(80+ "header",81+ [82+ "multipart/form-data; charset=utf-8",83+ "multipart/form-data; charset=utf-8; ",84+ ],85+)86+def test_multipart_header_without_boundary(header: str) -> None:87+ client = httpx.Client(transport=httpx.MockTransport(echo_request_content))88+89+ files = {"file": io.BytesIO(b"<file content>")}90+ headers = {"content-type": header}91+ response = client.post("http://127.0.0.1:8000/", files=files, headers=headers)92+93+ assert response.status_code == 20094+ assert response.request.headers["Content-Type"] == header95+96+97 @pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))98 def test_multipart_invalid_key(key):99 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))100 329 unmodified lines