Skip to content
Myr

Consistent multidict methods (#1089)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Consistent multidict methods * Consistent multidict methods and behaviour * Update httpx/_models.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Update httpx/_models.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com>

authored by Tom Christie · committed by GitHub · parent dba83d4 · Browse files · 3 files+80 added−24 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

3 files+80 added−24 removed

  • tests:+10 added−9 removed
  • other:+70 added−15 removed

3 files+80 added−24 removed

modified:httpx/_models.py+70 added-15 removed
2 unmodified lines
3import email.message4import json as jsonlib5import typing6import urllib.request7import warnings8from collections.abc import MutableMapping9from http.cookiejar import Cookie, CookieJar10from urllib.parse import parse_qsl, urlencode11
228 unmodified lines
240241 self._list = [(str(k), str_query_param(v)) for k, v in items]242 self._dict = {str(k): str_query_param(v) for k, v in items}243243 def getlist(self, key: typing.Any) -> typing.List[str]:244 return [item_value for item_key, item_value in self._list if item_key == key]245244 def keys(self) -> typing.KeysView:245 return self._dict.keys()246247 def values(self) -> typing.ValuesView:248 return self._dict.values()249250 def items(self) -> typing.ItemsView:251 """252 Return all items in the query params. If a key occurs more than once253 only the first item for that key is returned.254 """255 return self._dict.items()256257 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:258 """259 Return all items in the query params. Allow duplicate keys to occur.260 """261 return list(self._list)262263 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:264 """265 Get a value from the query param for a given key. If the key occurs266 more than once, then only the first value is returned.267 """268 if key in self._dict:269 return self._dict[key]270 return default271272 def get_list(self, key: typing.Any) -> typing.List[str]:273 """274 Get all values from the query param for a given key.275 """276 return [item_value for item_key, item_value in self._list if item_key == key]277278 def update(self, params: QueryParamTypes = None) -> None:279 if not params:280 return281
47 unmodified lines
329 class_name = self.__class__.__name__330 query_string = str(self)331 return f"{class_name}({query_string!r})"332333 def getlist(self, key: typing.Any) -> typing.List[str]:334 message = (335 "QueryParams.getlist() is pending deprecation. Use QueryParams.get_list()"336 )337 warnings.warn(message, PendingDeprecationWarning)338 return self.get_list(key)339340341class Headers(typing.MutableMapping[str, str]):342 """343 HTTP headers, as a case-insensitive multi-dict.344 """
12 unmodified lines
357 self._list = [358 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))359 for k, v in headers360 ]361362 self._dict = {} # type: typing.Dict[bytes, bytes]363 for key, value in self._list:364 if key in self._dict:365 self._dict[key] = self._dict[key] + b", " + value366 else:367 self._dict[key] = value368369 self._encoding = encoding370371 @property372 def encoding(self) -> str:
32 unmodified lines
405 """406 return self._list407408 def keys(self) -> typing.List[str]: # type: ignore379 return [key.decode(self.encoding) for key, value in self._list]409 return [key.decode(self.encoding) for key in self._dict.keys()]410411 def values(self) -> typing.List[str]: # type: ignore382 return [value.decode(self.encoding) for key, value in self._list]412 return [value.decode(self.encoding) for value in self._dict.values()]413414 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore415 """416 Return a list of `(key, value)` pairs of headers. Concatenate headers417 into a single comma seperated value when a key occurs multiple times.418 """419 return [420 (key.decode(self.encoding), value.decode(self.encoding))421 for key, value in self._dict.items()422 ]423424 def multi_items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore425 """426 Return a list of `(key, value)` pairs of headers. Allow multiple427 occurences of the same key without concatenating into a single428 comma seperated value.429 """430 return [431 (key.decode(self.encoding), value.decode(self.encoding))432 for key, value in self._list433 ]434435 def get(self, key: str, default: typing.Any = None) -> typing.Any:436 """437 Return a header value. If multiple occurences of the header occur438 then concatenate them together with commas.439 """440 try:441 return self[key]442 except KeyError:443 return default444396 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:445 def get_list(self, key: str, split_commas: bool = False) -> typing.List[str]:446 """398 Return multiple header values.447 Return a list of all header values for a given key.448 If `split_commas=True` is passed, then any comma seperated header449 values are split into multiple return strings.450 """451 get_header_key = key.lower().encode(self.encoding)452453 values = [
44 unmodified lines
498 """499 set_key = key.lower().encode(self._encoding or "utf-8")500 set_value = value.encode(self._encoding or "utf-8")501502 self._dict[set_key] = set_value503504 found_indexes = []505 for idx, (item_key, _) in enumerate(self._list):506 if item_key == set_key:507 found_indexes.append(idx)
12 unmodified lines
520 Remove the header `key`.521 """522 del_key = key.lower().encode(self.encoding)523524 del self._dict[del_key]525526 pop_indexes = []527 for idx, (item_key, _) in enumerate(self._list):528 if item_key == del_key:529 pop_indexes.append(idx)475 if not pop_indexes:476 raise KeyError(key)530531 for idx in reversed(pop_indexes):532 del self._list[idx]533534 def __contains__(self, key: typing.Any) -> bool:482 get_header_key = key.lower().encode(self.encoding)483 for header_key, _ in self._list:484 if header_key == get_header_key:485 return True486 return False535 header_key = key.lower().encode(self.encoding)536 return header_key in self._dict537538 def __iter__(self) -> typing.Iterator[typing.Any]:539 return iter(self.keys())540
11 unmodified lines
552 encoding_str = ""553 if self.encoding != "ascii":554 encoding_str = f", encoding={self.encoding!r}"555506 as_list = list(obfuscate_sensitive_headers(self.items()))556 as_list = list(obfuscate_sensitive_headers(self.multi_items()))557 as_dict = dict(as_list)558559 no_duplicate_keys = len(as_dict) == len(as_list)560 if no_duplicate_keys:561 return f"{class_name}({as_dict!r}{encoding_str})"562 return f"{class_name}({as_list!r}{encoding_str})"563564 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:565 message = "Headers.getlist() is pending deprecation. Use Headers.get_list()"566 warnings.warn(message, PendingDeprecationWarning)567 return self.get_list(key, split_commas=split_commas)568569570USER_AGENT = f"python-httpx/{__version__}"571ACCEPT_ENCODING = ", ".join(572 [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]573)
617 unmodified lines
modified:tests/models/test_headers.py+9 added-8 removed
11 unmodified lines
12 assert "c" not in h13 assert h["a"] == "123, 456"14 assert h.get("a") == "123, 456"15 assert h.get("nope", default=None) is None16 assert h.getlist("a") == ["123", "456"]17 assert h.keys() == ["a", "a", "b"]18 assert h.values() == ["123", "456", "789"]19 assert h.items() == [("a", "123"), ("a", "456"), ("b", "789")]20 assert list(h) == ["a", "a", "b"]16 assert h.get_list("a") == ["123", "456"]17 assert h.keys() == ["a", "b"]18 assert h.values() == ["123, 456", "789"]19 assert h.items() == [("a", "123, 456"), ("b", "789")]20 assert h.multi_items() == [("a", "123"), ("a", "456"), ("b", "789")]21 assert list(h) == ["a", "b"]22 assert dict(h) == {"a": "123, 456", "b": "789"}23 assert repr(h) == "Headers([('a', '123'), ('a', '456'), ('b', '789')])"24 assert h == httpx.Headers([("a", "123"), ("b", "789"), ("a", "456")])25 assert h != [("a", "123"), ("A", "456"), ("b", "789")]
127 unmodified lines
153154155def test_multiple_headers():156 """156 Most headers should split by commas for `getlist`, except 'Set-Cookie'.157 `Headers.get_list` should support both split_commas=False and split_commas=True.158 """159 h = httpx.Headers([("set-cookie", "a, b"), ("set-cookie", "c")])159 h.getlist("Set-Cookie") == ["a, b", "b"]160 assert h.get_list("Set-Cookie") == ["a, b", "c"]161162 h = httpx.Headers([("vary", "a, b"), ("vary", "c")])162 h.getlist("Vary") == ["a", "b", "c"]163 assert h.get_list("Vary", split_commas=True) == ["a", "b", "c"]164165166@pytest.mark.parametrize("header", ["authorization", "proxy-authorization"])167def test_sensitive_headers(header):
6 unmodified lines
modified:tests/models/test_queryparams.py+1 added-1 removed
17 unmodified lines
18 assert "c" not in q19 assert q["a"] == "456"20 assert q.get("a") == "456"21 assert q.get("nope", default=None) is None22 assert q.getlist("a") == ["123", "456"]22 assert q.get_list("a") == ["123", "456"]23 assert list(q.keys()) == ["a", "b"]24 assert list(q.values()) == ["456", "789"]25 assert list(q.items()) == [("a", "456"), ("b", "789")]26 assert len(q) == 2
61 unmodified lines