Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/14579.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed :py:meth:`aiohttp.FormData.add_field` mutating ``_is_multipart`` before argument validation completes -- by :user:`xtianWang`.
11 changes: 6 additions & 5 deletions aiohttp/formdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,6 @@ def add_field(
content_type: str | None = None,
filename: str | None = None,
) -> None:
if isinstance(value, (io.IOBase, bytes, bytearray, memoryview)):
self._is_multipart = True

_safe_header(name)
type_options: MultiDict[str] = MultiDict({"name": name})
if filename is not None and not isinstance(filename, str):
Expand All @@ -66,7 +63,6 @@ def add_field(
if filename is not None:
_safe_header(filename)
type_options["filename"] = filename
self._is_multipart = True

headers = {}
if content_type is not None:
Expand All @@ -76,9 +72,14 @@ def add_field(
)
_safe_header(content_type)
headers[hdrs.CONTENT_TYPE] = content_type
self._is_multipart = True

self._fields.append((type_options, headers, value))
if (
filename is not None
or content_type is not None
or isinstance(value, (io.IOBase, bytes, bytearray, memoryview))
):
self._is_multipart = True

def add_fields(self, *fields: Any) -> None:
to_add: deque[Any] = deque(fields)
Expand Down
11 changes: 11 additions & 0 deletions tests/test_formdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@ def test_formdata_multipart(buf: bytearray) -> None:
assert form.is_multipart


@pytest.mark.parametrize(("value", "filename"), [(b"data", None), ("data", "file.txt")])
def test_rejected_field_preserves_form_encoding(
value: bytes | str, filename: str | None
) -> None:
form = FormData({"key": "value"})
with pytest.raises(TypeError, match="content_type must be an instance of str"):
form.add_field("file", value, filename=filename, content_type=42) # type: ignore[arg-type]

assert form().content_type == "application/x-www-form-urlencoded"


def test_form_data_is_multipart_param(buf: bytearray) -> None:
form = FormData(default_to_multipart=True)
assert form.is_multipart
Expand Down
Loading