Tweak QueryParams implementation (#1598)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by GitHub · parent 6e55ca1 · Browse files · 2 files·+26 added−37 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+26 added−37 removed
- tests:+5 added−5 removed
- other:+21 added−32 removed
Provenance
- Commit
8fe32c5- Tree
43c8716- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
6e55ca1
2 files changed+26 added−37 removed
modified:httpx/_models.py+21 added-32 removed
510 unmodified lines511 items = value512 else:513 items = flatten_queryparams(value)514 515- self._list = [(str(k), primitive_value_to_str(v)) for k, v in items]516- self._dict = {str(k): primitive_value_to_str(v) for k, v in items}515+ self._dict: typing.Dict[str, typing.List[str]] = {}516+ for item in items:517+ k, v = item518+ if str(k) not in self._dict:519+ self._dict[str(k)] = [primitive_value_to_str(v)]520+ else:521+ self._dict[str(k)].append(primitive_value_to_str(v))522 523 def keys(self) -> typing.KeysView:524 return self._dict.keys()525 526 def values(self) -> typing.ValuesView:522- return self._dict.values()527+ return {k: v[0] for k, v in self._dict.items()}.values()528 529 def items(self) -> typing.ItemsView:530 """531 Return all items in the query params. If a key occurs more than once532 only the first item for that key is returned.533 """529- return self._dict.items()534+ return {k: v[0] for k, v in self._dict.items()}.items()535 536 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:537 """538 Return all items in the query params. Allow duplicate keys to occur.539 """535- return list(self._list)540+ multi_items: typing.List[typing.Tuple[str, str]] = []541+ for k, v in self._dict.items():542+ multi_items.extend([(k, i) for i in v])543+ return multi_items544 545 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:546 """547 Get a value from the query param for a given key. If the key occurs548 more than once, then only the first value is returned.549 """550 if key in self._dict:543- return self._dict[key]551+ return self._dict[key][0]552 return default553 554 def get_list(self, key: typing.Any) -> typing.List[str]:555 """556 Get all values from the query param for a given key.557 """550- return [item_value for item_key, item_value in self._list if item_key == key]558+ return list(self._dict.get(key, []))559 560 def update(self, params: QueryParamTypes = None) -> None:561 if not params:562 return563 564 params = QueryParams(params)557- for param in params:558- item, *extras = params.get_list(param)559- self[param] = item560- if extras:561- self._list.extend((param, e) for e in extras)562- # ensure getter matches merged QueryParams getter563- self._dict[param] = params[param]565+ for k in params.keys():566+ self._dict[k] = params.get_list(k)567 568 def __getitem__(self, key: typing.Any) -> str:566- return self._dict[key]569+ return self._dict[key][0]570 571 def __setitem__(self, key: str, value: str) -> None:569- self._dict[key] = value572+ self._dict[key] = [value]573 571- found_indexes = []572- for idx, (item_key, _) in enumerate(self._list):573- if item_key == key:574- found_indexes.append(idx)575-576- for idx in reversed(found_indexes[1:]):577- del self._list[idx]578-579- if found_indexes:580- idx = found_indexes[0]581- self._list[idx] = (key, value)582- else:583- self._list.append((key, value))584-574 def __contains__(self, key: typing.Any) -> bool:575 return key in self._dict576 577 def __iter__(self) -> typing.Iterator[typing.Any]:4 unmodified lines582 583 def __eq__(self, other: typing.Any) -> bool:584 if not isinstance(other, self.__class__):585 return False597- return sorted(self._list) == sorted(other._list)586+ return sorted(self.multi_items()) == sorted(other.multi_items())587 588 def __str__(self) -> str:600- return urlencode(self._list)589+ return urlencode(self.multi_items())590 591 def __repr__(self) -> str:592 class_name = self.__class__.__name__593 query_string = str(self)1026 unmodified linesmodified:tests/models/test_queryparams.py+5 added-5 removed
16 unmodified lines17 q = httpx.QueryParams(source)18 assert "a" in q19 assert "A" not in q20 assert "c" not in q21- assert q["a"] == "456"22- assert q.get("a") == "456"21+ assert q["a"] == "123"22+ assert q.get("a") == "123"23 assert q.get("nope", default=None) is None24 assert q.get_list("a") == ["123", "456"]25 26 assert list(q.keys()) == ["a", "b"]27- assert list(q.values()) == ["456", "789"]28- assert list(q.items()) == [("a", "456"), ("b", "789")]27+ assert list(q.values()) == ["123", "789"]28+ assert list(q.items()) == [("a", "123"), ("b", "789")]29 assert len(q) == 230 assert list(q) == ["a", "b"]31- assert dict(q) == {"a": "456", "b": "789"}31+ assert dict(q) == {"a": "123", "b": "789"}32 assert str(q) == "a=123&a=456&b=789"33 assert repr(q) == "QueryParams('a=123&a=456&b=789')"34 assert httpx.QueryParams({"a": "123", "b": "456"}) == httpx.QueryParams(35 [("a", "123"), ("b", "456")]59 unmodified lines