Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Handle int, float, bool, and None for multipart or urlencoded data
  • Loading branch information
lovelydinosaur committed Mar 25, 2021
commit 30dd7d3c7c7023fc516e65c7a223006f1238bed8
13 changes: 9 additions & 4 deletions httpx/_multipart.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
format_form_param,
guess_content_type,
peek_filelike_length,
primitive_value_to_str,
to_bytes,
)

Expand All @@ -17,17 +18,21 @@ class DataField:
A single form field item, within a multipart form field.
"""

def __init__(self, name: str, value: typing.Union[str, bytes]) -> None:
def __init__(
self, name: str, value: typing.Union[str, bytes, int, float, None]
) -> None:
if not isinstance(name, str):
raise TypeError(
f"Invalid type for name. Expected str, got {type(name)}: {name!r}"
)
if not isinstance(value, (str, bytes)):
if value is not None and not isinstance(value, (str, bytes, int, float)):
raise TypeError(
f"Invalid type for value. Expected str or bytes, got {type(value)}: {value!r}"
f"Invalid type for value. Expected primitive type, got {type(value)}: {value!r}"
)
self.name = name
self.value = value
self.value: typing.Union[str, bytes] = (
value if isinstance(value, bytes) else primitive_value_to_str(value)
)

def render_headers(self) -> bytes:
if not hasattr(self, "_headers"):
Expand Down
6 changes: 5 additions & 1 deletion tests/test_multipart.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def test_multipart_invalid_key(key):
assert repr(key) in str(e.value)


@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))
@pytest.mark.parametrize(("value"), (object(), {"key": "value"}))
def test_multipart_invalid_value(value):
client = httpx.Client(transport=httpx.MockTransport(echo_request_content))

Expand Down Expand Up @@ -104,6 +104,8 @@ def test_multipart_encode(tmp_path: typing.Any) -> None:
"b": b"C",
"c": ["11", "22", "33"],
"d": "",
"e": True,
"f": "",
}
files = {"file": ("name.txt", open(path, "rb"))}

Expand All @@ -120,6 +122,8 @@ def test_multipart_encode(tmp_path: typing.Any) -> None:
'--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'
'--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'
'--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'
'--{0}\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'
'--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'
'--{0}\r\nContent-Disposition: form-data; name="file";'
' filename="name.txt"\r\n'
"Content-Type: text/plain\r\n\r\n<file content>\r\n"
Expand Down