Add QueryParams class
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parent 698cb5a · Browse files · 4 files·+124 added−11 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+124 added−11 removed
- tests:+33 added−0 removed
- other:+91 added−11 removed
Provenance
- Commit
211bef1- Tree
f48e15e- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
698cb5a
4 files changed+124 added−11 removed
modified:httpcore/backends/default.py+7 added-6 removed
26 unmodified lines27 #28 # Clients which have been opened using a `with` block, or which have29 # had `close()` closed, will not exhibit this issue in the first place.30 31-_write = asyncio.selector_events._SelectorSocketTransport.write31 33-def _fixed_write(self, exc):32+_write = asyncio.selector_events._SelectorSocketTransport.write # type: ignore33+34+35+def _fixed_write(self, data: bytes) -> None: # type: ignore36 if not self._loop.is_closed():35- _write(self, exc)37+ _write(self, data)38 37-asyncio.selector_events._SelectorSocketTransport.write = _fixed_write39 40+asyncio.selector_events._SelectorSocketTransport.write = _fixed_write # type: ignore41 42+43 class Reader(BaseReader):44 def __init__(45 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig46 ) -> None:93 unmodified lines140 ident = ssl_object.selected_alpn_protocol()141 if ident is None:142 ident = ssl_object.selected_npn_protocol()143 141- stream_writer.transport.set_write_buffer_limits(high=0, low=0)142-144 reader = Reader(stream_reader=stream_reader, timeout=timeout)145 writer = Writer(stream_writer=stream_writer, timeout=timeout)146 protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11147 1 unmodified linemodified:httpcore/__init__.py+1 added-1 removed
21 unmodified lines22 Timeout,23 TooManyRedirects,24 )25 from .interfaces import Adapter, BaseReader, BaseWriter26-from .models import URL, Headers, Origin, Request, Response26+from .models import URL, Headers, Origin, QueryParams, Request, Response27 28 __version__ = "0.2.1"modified:httpcore/models.py+83 added-4 removed
1 import cgi2 import typing3+from urllib.parse import parse_qsl, urlencode4 5 import chardet6 import idna7 import rfc398622 unmodified lines30 )31 32 URLTypes = typing.Union["URL", str]33 34+QueryParamTypes = typing.Union[35+ "QueryParams",36+ typing.Mapping[str, str],37+ typing.List[typing.Tuple[typing.Any, typing.Any]],38+ str,39+]40+41 HeaderTypes = typing.Union[42 "Headers",43 typing.Dict[typing.AnyStr, typing.AnyStr],44 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],2 unmodified lines47 ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]48 49 50 class URL:43- def __init__(self, url: URLTypes, allow_relative: bool = False) -> None:51+ def __init__(52+ self, url: URLTypes, allow_relative: bool = False, params: QueryParamTypes = None53+ ) -> None:54 if isinstance(url, rfc3986.uri.URIReference):55 self.components = url56 elif isinstance(url, str):57 self.components = rfc3986.api.uri_reference(url)107 unmodified lines165 return f"{class_name}({url_str!r})"166 167 168 class Origin:169+ """170+ The URL scheme and authority information, as a comparable, hashable object.171+ """172+173 def __init__(self, url: URLTypes) -> None:174 if not isinstance(url, URL):175 url = URL(url)176 self.is_ssl = url.is_ssl11 unmodified lines188 def __hash__(self) -> int:189 return hash((self.is_ssl, self.host, self.port))190 191 192+class QueryParams(typing.Mapping):193+ def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:194+ assert len(args) < 2, "Too many arguments."195+ assert not (args and kwargs), "Cannot mix named and unnamed arguments."196+197+ value = args[0] if args else kwargs198+199+ if isinstance(value, str):200+ items = parse_qsl(value)201+ elif isinstance(value, QueryParams):202+ items = value.multi_items()203+ elif isinstance(value, list):204+ items = value205+ else:206+ items = value.items() # type: ignore207+208+ self._list = [(str(k), str(v)) for k, v in items]209+ self._dict = {str(k): str(v) for k, v in items}210+211+ def getlist(self, key: typing.Any) -> typing.List[str]:212+ return [item_value for item_key, item_value in self._list if item_key == key]213+214+ def keys(self) -> typing.KeysView:215+ return self._dict.keys()216+217+ def values(self) -> typing.ValuesView:218+ return self._dict.values()219+220+ def items(self) -> typing.ItemsView:221+ return self._dict.items()222+223+ def multi_items(self) -> typing.List[typing.Tuple[str, str]]:224+ return list(self._list)225+226+ def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:227+ if key in self._dict:228+ return self._dict[key]229+ return default230+231+ def __getitem__(self, key: typing.Any) -> str:232+ return self._dict[key]233+234+ def __contains__(self, key: typing.Any) -> bool:235+ return key in self._dict236+237+ def __iter__(self) -> typing.Iterator[typing.Any]:238+ return iter(self.keys())239+240+ def __len__(self) -> int:241+ return len(self._dict)242+243+ def __eq__(self, other: typing.Any) -> bool:244+ if not isinstance(other, self.__class__):245+ return False246+ return sorted(self._list) == sorted(other._list)247+248+ def __str__(self) -> str:249+ return urlencode(self._list)250+251+ def __repr__(self) -> str:252+ class_name = self.__class__.__name__253+ query_string = str(self)254+ return f"{class_name}({query_string!r})"255+256+257 class Headers(typing.MutableMapping[str, str]):258 """180- A case-insensitive multidict.259+ HTTP headers, as a case-insensitive multi-dict.260 """261 262 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:263 if headers is None:14 unmodified lines278 279 @property280 def encoding(self) -> str:281 """203- Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be204- seen in the wild.282+ Header encoding is mandated as ascii, but we allow fallbacks to utf-8283+ or iso-8859-1.284 """285 if self._encoding is None:286 for encoding in ["ascii", "utf-8"]:287 for key, value in self.raw:446 unmodified linesadded:tests/models/test_queryparams.py+33 added
1+from httpcore import QueryParams2+3+4+def test_queryparams():5+ q = QueryParams("a=123&a=456&b=789")6+ assert "a" in q7+ assert "A" not in q8+ assert "c" not in q9+ assert q["a"] == "456"10+ assert q.get("a") == "456"11+ assert q.get("nope", default=None) is None12+ assert q.getlist("a") == ["123", "456"]13+ assert list(q.keys()) == ["a", "b"]14+ assert list(q.values()) == ["456", "789"]15+ assert list(q.items()) == [("a", "456"), ("b", "789")]16+ assert len(q) == 217+ assert list(q) == ["a", "b"]18+ assert dict(q) == {"a": "456", "b": "789"}19+ assert str(q) == "a=123&a=456&b=789"20+ assert repr(q) == "QueryParams('a=123&a=456&b=789')"21+ assert QueryParams({"a": "123", "b": "456"}) == QueryParams(22+ [("a", "123"), ("b", "456")]23+ )24+ assert QueryParams({"a": "123", "b": "456"}) == QueryParams("a=123&b=456")25+ assert QueryParams({"a": "123", "b": "456"}) == QueryParams(26+ {"b": "456", "a": "123"}27+ )28+ assert QueryParams() == QueryParams({})29+ assert QueryParams([("a", "123"), ("a", "456")]) == QueryParams("a=123&a=456")30+ assert QueryParams({"a": "123", "b": "456"}) != "invalid"31+32+ q = QueryParams([("a", "123"), ("a", "456")])33+ assert QueryParams(q) == q