Skip to content
Myr

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

4 files+124 added−11 removed

modified:httpcore/backends/default.py+7 added-6 removed
26 unmodified lines
27#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.3031_write = asyncio.selector_events._SelectorSocketTransport.write3133def _fixed_write(self, exc):32_write = asyncio.selector_events._SelectorSocketTransport.write # type: ignore333435def _fixed_write(self, data: bytes) -> None: # type: ignore36 if not self._loop.is_closed():35 _write(self, exc)37 _write(self, data)3837asyncio.selector_events._SelectorSocketTransport.write = _fixed_write3940asyncio.selector_events._SelectorSocketTransport.write = _fixed_write # type: ignore414243class Reader(BaseReader):44 def __init__(45 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig46 ) -> None:
93 unmodified lines
140 ident = ssl_object.selected_alpn_protocol()141 if ident is None:142 ident = ssl_object.selected_npn_protocol()143141 stream_writer.transport.set_write_buffer_limits(high=0, low=0)142144 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 line
modified:httpcore/__init__.py+1 added-1 removed
21 unmodified lines
22 Timeout,23 TooManyRedirects,24)25from .interfaces import Adapter, BaseReader, BaseWriter26from .models import URL, Headers, Origin, Request, Response26from .models import URL, Headers, Origin, QueryParams, Request, Response2728__version__ = "0.2.1"
modified:httpcore/models.py+83 added-4 removed
1import cgi2import typing3from urllib.parse import parse_qsl, urlencode45import chardet6import idna7import rfc3986
22 unmodified lines
30)3132URLTypes = typing.Union["URL", str]3334QueryParamTypes = typing.Union[35 "QueryParams",36 typing.Mapping[str, str],37 typing.List[typing.Tuple[typing.Any, typing.Any]],38 str,39]4041HeaderTypes = typing.Union[42 "Headers",43 typing.Dict[typing.AnyStr, typing.AnyStr],44 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],
2 unmodified lines
47ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]484950class 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 lines
165 return f"{class_name}({url_str!r})"166167168class Origin:169 """170 The URL scheme and authority information, as a comparable, hashable object.171 """172173 def __init__(self, url: URLTypes) -> None:174 if not isinstance(url, URL):175 url = URL(url)176 self.is_ssl = url.is_ssl
11 unmodified lines
188 def __hash__(self) -> int:189 return hash((self.is_ssl, self.host, self.port))190191192class 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."196197 value = args[0] if args else kwargs198199 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: ignore207208 self._list = [(str(k), str(v)) for k, v in items]209 self._dict = {str(k): str(v) for k, v in items}210211 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]213214 def keys(self) -> typing.KeysView:215 return self._dict.keys()216217 def values(self) -> typing.ValuesView:218 return self._dict.values()219220 def items(self) -> typing.ItemsView:221 return self._dict.items()222223 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:224 return list(self._list)225226 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 default230231 def __getitem__(self, key: typing.Any) -> str:232 return self._dict[key]233234 def __contains__(self, key: typing.Any) -> bool:235 return key in self._dict236237 def __iter__(self) -> typing.Iterator[typing.Any]:238 return iter(self.keys())239240 def __len__(self) -> int:241 return len(self._dict)242243 def __eq__(self, other: typing.Any) -> bool:244 if not isinstance(other, self.__class__):245 return False246 return sorted(self._list) == sorted(other._list)247248 def __str__(self) -> str:249 return urlencode(self._list)250251 def __repr__(self) -> str:252 class_name = self.__class__.__name__253 query_string = str(self)254 return f"{class_name}({query_string!r})"255256257class Headers(typing.MutableMapping[str, str]):258 """180 A case-insensitive multidict.259 HTTP headers, as a case-insensitive multi-dict.260 """261262 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:263 if headers is None:
14 unmodified lines
278279 @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 lines
added:tests/models/test_queryparams.py+33 added
1from httpcore import QueryParams234def 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"3132 q = QueryParams([("a", "123"), ("a", "456")])33 assert QueryParams(q) == q