Allow lists in query params (#386)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Florimond Manca · committed by Seth Michael Larson · parent 31730e7 · Browse files · 3 files·+47 added−6 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+47 added−6 removed
- tests:+12 added−2 removed
- other:+35 added−4 removed
Provenance
- Commit
57ae7ea- Tree
9e250c4- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
Seth Michael Larson <sethmichaellarson@gmail.com>- Parent
31730e7
3 files changed+47 added−6 removed
modified:httpx/models.py+5 added-3 removed
30 unmodified lines31 )32 from .multipart import multipart_encode33 from .status_codes import StatusCode34 from .utils import (35+ flatten_queryparams,36 guess_json_utf,37 is_known_encoding,38 normalize_header_key,39 normalize_header_value,11 unmodified lines51 URLTypes = typing.Union["URL", str]52 53 QueryParamTypes = typing.Union[54 "QueryParams",54- typing.Mapping[str, PrimitiveData],55+ typing.Mapping[str, typing.Union[PrimitiveData, typing.Sequence[PrimitiveData]]],56 typing.List[typing.Tuple[str, PrimitiveData]],57 str,58 ]59 251 unmodified lines311 assert not (args and kwargs), "Cannot mix named and unnamed arguments."312 313 value = args[0] if args else kwargs314 315+ items: typing.Sequence[typing.Tuple[str, PrimitiveData]]316 if isinstance(value, str):317 items = parse_qsl(value)318 elif isinstance(value, QueryParams):319 items = value.multi_items()320 elif isinstance(value, list):319- items = value # type: ignore321+ items = value322 else:321- items = value.items() # type: ignore323+ items = flatten_queryparams(value)324 325 self._list = [(str(k), str_query_param(v)) for k, v in items]326 self._dict = {str(k): str_query_param(v) for k, v in items}327 996 unmodified linesmodified:httpx/utils.py+30 added-1 removed
1 import codecs2+import collections3 import logging4 import netrc5 import os6 import re4 unmodified lines11 from time import perf_counter12 from types import TracebackType13 from urllib.request import getproxies14 15+if typing.TYPE_CHECKING: # pragma: no cover16+ from .models import PrimitiveData17 18+19 def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:20 """21 Coerce str/bytes into a strictly byte-wise HTTP header key.22 """10 unmodified lines33 return value34 return value.encode(encoding or "ascii")35 36 33-def str_query_param(value: typing.Optional[typing.Union[str, int, float, bool]]) -> str:37+def str_query_param(value: "PrimitiveData") -> str:38 """39 Coerce a primitive data type into a string value for query params.40 41 Note that we prefer JSON-style 'true'/'false' for boolean values here.217 unmodified lines259 def unquote(value: str) -> str:260 return value[1:-1] if value[0] == value[-1] == '"' else value261 262 263+def flatten_queryparams(264+ queryparams: typing.Mapping[265+ str, typing.Union["PrimitiveData", typing.Sequence["PrimitiveData"]]266+ ]267+) -> typing.List[typing.Tuple[str, "PrimitiveData"]]:268+ """269+ Convert a mapping of query params into a flat list of two-tuples270+ representing each item.271+272+ Example:273+ >>> flatten_queryparams_values({"q": "httpx", "tag": ["python", "dev"]})274+ [("q", "httpx), ("tag", "python"), ("tag", "dev")]275+ """276+ items = []277+278+ for k, v in queryparams.items():279+ if isinstance(v, collections.abc.Sequence) and not isinstance(v, (str, bytes)):280+ for u in v:281+ items.append((k, u))282+ else:283+ items.append((k, typing.cast("PrimitiveData", v)))284+285+ return items286+287+288 class ElapsedTimer:289 def __init__(self) -> None:290 self.start: float = perf_counter()291 self.end: typing.Optional[float] = None79 unmodified linesmodified:tests/models/test_queryparams.py+12 added-2 removed
1+import pytest2+3 from httpx import QueryParams4 5 6+@pytest.mark.parametrize(7+ "source",8+ [9+ "a=123&a=456&b=789",10+ {"a": ["123", "456"], "b": 789},11+ {"a": ("123", "456"), "b": 789},12+ ],13+)4-def test_queryparams():5- q = QueryParams("a=123&a=456&b=789")14+def test_queryparams(source):15+ q = QueryParams(source)16 assert "a" in q17 assert "A" not in q18 assert "c" not in q19 assert q["a"] == "456"55 unmodified lines