Handle `data={"key": [None|int|float|bool]}` cases. (#1539)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Fix Content-Length for unicode file contents with multipart * Handle bool and None cases for URLEncoded data * Handle int, float, bool, and None for multipart or urlencoded data * Update httpx/_utils.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com>
authored by Tom Christie · committed by GitHub · parent c75ddc2 · Browse files · 6 files·+78 added−11 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Florimond Manca <florimond.manca@gmail.com>
Diff stats
6 files+78 added−11 removed
- tests:+56 added−1 removed
- other:+22 added−10 removed
Provenance
- Commit
c26425a- Tree
0a905d8- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
c75ddc2
6 files changed+78 added−11 removed
modified:httpx/_content.py+8 added-1 removed
19 unmodified lines20 RequestData,21 RequestFiles,22 ResponseContent,23 )24+from ._utils import primitive_value_to_str25 26 27 class PlainByteStream:28 """77 unmodified lines106 107 def encode_urlencoded_data(108 data: dict,109 ) -> Tuple[Dict[str, str], ByteStream]:110+ plain_data = []111+ for key, value in data.items():112+ if isinstance(value, (list, tuple)):113+ plain_data.extend([(key, primitive_value_to_str(item)) for item in value])114+ else:115+ plain_data.append((key, primitive_value_to_str(value)))109- body = urlencode(data, doseq=True).encode("utf-8")116+ body = urlencode(plain_data, doseq=True).encode("utf-8")117 content_length = str(len(body))118 content_type = "application/x-www-form-urlencoded"119 headers = {"Content-Length": content_length, "Content-Type": content_type}120 return headers, PlainByteStream(body)87 unmodified linesmodified:httpx/_models.py+3 added-3 removed
52 unmodified lines53 normalize_header_key,54 normalize_header_value,55 obfuscate_sensitive_headers,56 parse_header_links,57- str_query_param,57+ primitive_value_to_str,58 )59 60 61 class URL:387 unmodified lines449 items = value450 else:451 items = flatten_queryparams(value)452 453- self._list = [(str(k), str_query_param(v)) for k, v in items]454- self._dict = {str(k): str_query_param(v) for k, v in items}453+ self._list = [(str(k), primitive_value_to_str(v)) for k, v in items]454+ self._dict = {str(k): primitive_value_to_str(v) for k, v in items}455 456 def keys(self) -> typing.KeysView:457 return self._dict.keys()458 1081 unmodified linesmodified:httpx/_multipart.py+9 added-4 removed
6 unmodified lines7 from ._utils import (8 format_form_param,9 guess_content_type,10 peek_filelike_length,11+ primitive_value_to_str,12 to_bytes,13 )14 15 1 unmodified line17 """18 A single form field item, within a multipart form field.19 """20 20- def __init__(self, name: str, value: typing.Union[str, bytes]) -> None:21+ def __init__(22+ self, name: str, value: typing.Union[str, bytes, int, float, None]23+ ) -> None:24 if not isinstance(name, str):25 raise TypeError(26 f"Invalid type for name. Expected str, got {type(name)}: {name!r}"27 )25- if not isinstance(value, (str, bytes)):28+ if value is not None and not isinstance(value, (str, bytes, int, float)):29 raise TypeError(27- f"Invalid type for value. Expected str or bytes, got {type(value)}: {value!r}"30+ f"Invalid type for value. Expected primitive type, got {type(value)}: {value!r}"31 )32 self.name = name30- self.value = value33+ self.value: typing.Union[str, bytes] = (34+ value if isinstance(value, bytes) else primitive_value_to_str(value)35+ )36 37 def render_headers(self) -> bytes:38 if not hasattr(self, "_headers"):39 name = format_form_param("name", self.name)166 unmodified linesmodified:httpx/_utils.py+2 added-2 removed
54 unmodified lines55 return value56 return value.encode(encoding or "ascii")57 58 59-def str_query_param(value: "PrimitiveData") -> str:59+def primitive_value_to_str(value: "PrimitiveData") -> str:60 """61- Coerce a primitive data type into a string value for query params.61+ Coerce a primitive data type into a string value.62 63 Note that we prefer JSON-style 'true'/'false' for boolean values here.64 """65 if value is True:476 unmodified linesmodified:tests/test_content.py+51 added
138 unmodified lines139 assert async_content == b"Hello=world%21"140 141 142 @pytest.mark.asyncio143+async def test_urlencoded_boolean():144+ headers, stream = encode_request(data={"example": True})145+ assert isinstance(stream, typing.Iterable)146+ assert isinstance(stream, typing.AsyncIterable)147+148+ sync_content = b"".join([part for part in stream])149+ async_content = b"".join([part async for part in stream])150+151+ assert headers == {152+ "Content-Length": "12",153+ "Content-Type": "application/x-www-form-urlencoded",154+ }155+ assert sync_content == b"example=true"156+ assert async_content == b"example=true"157+158+159+@pytest.mark.asyncio160+async def test_urlencoded_none():161+ headers, stream = encode_request(data={"example": None})162+ assert isinstance(stream, typing.Iterable)163+ assert isinstance(stream, typing.AsyncIterable)164+165+ sync_content = b"".join([part for part in stream])166+ async_content = b"".join([part async for part in stream])167+168+ assert headers == {169+ "Content-Length": "8",170+ "Content-Type": "application/x-www-form-urlencoded",171+ }172+ assert sync_content == b"example="173+ assert async_content == b"example="174+175+176+@pytest.mark.asyncio177+async def test_urlencoded_list():178+ headers, stream = encode_request(data={"example": ["a", 1, True]})179+ assert isinstance(stream, typing.Iterable)180+ assert isinstance(stream, typing.AsyncIterable)181+182+ sync_content = b"".join([part for part in stream])183+ async_content = b"".join([part async for part in stream])184+185+ assert headers == {186+ "Content-Length": "32",187+ "Content-Type": "application/x-www-form-urlencoded",188+ }189+ assert sync_content == b"example=a&example=1&example=true"190+ assert async_content == b"example=a&example=1&example=true"191+192+193+@pytest.mark.asyncio194 async def test_multipart_files_content():195 files = {"file": io.BytesIO(b"<file content>")}196 headers, stream = encode_request(files=files, boundary=b"+++")197 assert isinstance(stream, typing.Iterable)213 unmodified linesmodified:tests/test_multipart.py+5 added-1 removed
55 unmodified lines56 assert "Invalid type for name" in str(e.value)57 assert repr(key) in str(e.value)58 59 60-@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))60+@pytest.mark.parametrize(("value"), (object(), {"key": "value"}))61 def test_multipart_invalid_value(value):62 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))63 64 data = {"text": value}38 unmodified lines103 "a": "1",104 "b": b"C",105 "c": ["11", "22", "33"],106 "d": "",107+ "e": True,108+ "f": "",109 }110 files = {"file": ("name.txt", open(path, "rb"))}111 112 with mock.patch("os.urandom", return_value=os.urandom(16)):8 unmodified lines121 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'122 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'123 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'124 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'125+ '--{0}\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'126+ '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'127 '--{0}\r\nContent-Disposition: form-data; name="file";'128 ' filename="name.txt"\r\n'129 "Content-Type: text/plain\r\n\r\n<file content>\r\n"130 "--{0}--\r\n"164 unmodified lines