Merge pull request #42 from encode/query-params
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add query params to the API.
authored by Tom Christie · committed by GitHub · parents 698cb5a, faededa · Browse files · 7 files·+179 added−22 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+179 added−22 removed
- tests:+43 added−0 removed
- other:+136 added−22 removed
Provenance
- Commit
3de0425- Tree
3c3ca88- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent 1
698cb5a- Parent 2
faededa
7 files changed+179 added−22 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/client.py+27 added-2 removed
13 unmodified lines14 SSLConfig,15 TimeoutConfig,16 )17 from .dispatch.connection_pool import ConnectionPool18-from .models import URL, ByteOrByteStream, HeaderTypes, Request, Response, URLTypes18+from .models import (19+ URL,20+ ByteOrByteStream,21+ HeaderTypes,22+ QueryParamTypes,23+ Request,24+ Response,25+ URLTypes,26+)27 28 29 class Client:30 def __init__(18 unmodified lines49 method: str,50 url: URLTypes,51 *,52 content: ByteOrByteStream = b"",53+ query_params: QueryParamTypes = None,54 headers: HeaderTypes = None,55 stream: bool = False,56 allow_redirects: bool = True,57 ssl: SSLConfig = None,58 timeout: TimeoutConfig = None,59 ) -> Response:51- request = Request(method, url, headers=headers, content=content)60+ request = Request(61+ method, url, query_params=query_params, headers=headers, content=content62+ )63 self.prepare_request(request)64 response = await self.send(65 request,66 stream=stream,6 unmodified lines73 async def get(74 self,75 url: URLTypes,76 *,77+ query_params: QueryParamTypes = None,78 headers: HeaderTypes = None,79 stream: bool = False,80 allow_redirects: bool = True,81 ssl: SSLConfig = None,1 unmodified line83 ) -> Response:84 return await self.request(85 "GET",86 url,87+ query_params=query_params,88 headers=headers,89 stream=stream,90 allow_redirects=allow_redirects,91 ssl=ssl,3 unmodified lines95 async def options(96 self,97 url: URLTypes,98 *,99+ query_params: QueryParamTypes = None,100 headers: HeaderTypes = None,101 stream: bool = False,102 allow_redirects: bool = True,103 ssl: SSLConfig = None,1 unmodified line105 ) -> Response:106 return await self.request(107 "OPTIONS",108 url,109+ query_params=query_params,110 headers=headers,111 stream=stream,112 allow_redirects=allow_redirects,113 ssl=ssl,3 unmodified lines117 async def head(118 self,119 url: URLTypes,120 *,121+ query_params: QueryParamTypes = None,122 headers: HeaderTypes = None,123 stream: bool = False,124 allow_redirects: bool = False, # Note: Differs to usual default.125 ssl: SSLConfig = None,1 unmodified line127 ) -> Response:128 return await self.request(129 "HEAD",130 url,131+ query_params=query_params,132 headers=headers,133 stream=stream,134 allow_redirects=allow_redirects,135 ssl=ssl,4 unmodified lines140 self,141 url: URLTypes,142 *,143 content: ByteOrByteStream = b"",144+ query_params: QueryParamTypes = None,145 headers: HeaderTypes = None,146 stream: bool = False,147 allow_redirects: bool = True,148 ssl: SSLConfig = None,2 unmodified lines151 return await self.request(152 "POST",153 url,154 content=content,155+ query_params=query_params,156 headers=headers,157 stream=stream,158 allow_redirects=allow_redirects,159 ssl=ssl,4 unmodified lines164 self,165 url: URLTypes,166 *,167 content: ByteOrByteStream = b"",168+ query_params: QueryParamTypes = None,169 headers: HeaderTypes = None,170 stream: bool = False,171 allow_redirects: bool = True,172 ssl: SSLConfig = None,2 unmodified lines175 return await self.request(176 "PUT",177 url,178 content=content,179+ query_params=query_params,180 headers=headers,181 stream=stream,182 allow_redirects=allow_redirects,183 ssl=ssl,4 unmodified lines188 self,189 url: URLTypes,190 *,191 content: ByteOrByteStream = b"",192+ query_params: QueryParamTypes = None,193 headers: HeaderTypes = None,194 stream: bool = False,195 allow_redirects: bool = True,196 ssl: SSLConfig = None,2 unmodified lines199 return await self.request(200 "PATCH",201 url,202 content=content,203+ query_params=query_params,204 headers=headers,205 stream=stream,206 allow_redirects=allow_redirects,207 ssl=ssl,4 unmodified lines212 self,213 url: URLTypes,214 *,215 content: ByteOrByteStream = b"",216+ query_params: QueryParamTypes = None,217 headers: HeaderTypes = None,218 stream: bool = False,219 allow_redirects: bool = True,220 ssl: SSLConfig = None,2 unmodified lines223 return await self.request(224 "DELETE",225 url,226 content=content,227+ query_params=query_params,228 headers=headers,229 stream=stream,230 allow_redirects=allow_redirects,231 ssl=ssl,40 unmodified linesmodified:httpcore/models.py+93 added-5 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,53+ url: URLTypes,54+ allow_relative: bool = False,55+ query_params: QueryParamTypes = None,56+ ) -> None:57 if isinstance(url, rfc3986.uri.URIReference):58 self.components = url59 elif isinstance(url, str):60 self.components = rfc3986.api.uri_reference(url)8 unmodified lines69 70 # Normalize scheme and domain name.71 self.components = self.components.normalize()72 73+ # Add any query parameters.74+ if query_params:75+ query_string = str(QueryParams(query_params))76+ self.components = self.components.copy_with(query=query_string)77+78 # Enforce absolute URLs by default.79 if not allow_relative:80 if not self.scheme:81 raise InvalidURL("No scheme included in URL.")91 unmodified lines173 return f"{class_name}({url_str!r})"174 175 176 class Origin:177+ """178+ The URL scheme and authority information, as a comparable, hashable object.179+ """180+181 def __init__(self, url: URLTypes) -> None:182 if not isinstance(url, URL):183 url = URL(url)184 self.is_ssl = url.is_ssl11 unmodified lines196 def __hash__(self) -> int:197 return hash((self.is_ssl, self.host, self.port))198 199 200+class QueryParams(typing.Mapping):201+ def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:202+ assert len(args) < 2, "Too many arguments."203+ assert not (args and kwargs), "Cannot mix named and unnamed arguments."204+205+ value = args[0] if args else kwargs206+207+ if isinstance(value, str):208+ items = parse_qsl(value)209+ elif isinstance(value, QueryParams):210+ items = value.multi_items()211+ elif isinstance(value, list):212+ items = value213+ else:214+ items = value.items() # type: ignore215+216+ self._list = [(str(k), str(v)) for k, v in items]217+ self._dict = {str(k): str(v) for k, v in items}218+219+ def getlist(self, key: typing.Any) -> typing.List[str]:220+ return [item_value for item_key, item_value in self._list if item_key == key]221+222+ def keys(self) -> typing.KeysView:223+ return self._dict.keys()224+225+ def values(self) -> typing.ValuesView:226+ return self._dict.values()227+228+ def items(self) -> typing.ItemsView:229+ return self._dict.items()230+231+ def multi_items(self) -> typing.List[typing.Tuple[str, str]]:232+ return list(self._list)233+234+ def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:235+ if key in self._dict:236+ return self._dict[key]237+ return default238+239+ def __getitem__(self, key: typing.Any) -> str:240+ return self._dict[key]241+242+ def __contains__(self, key: typing.Any) -> bool:243+ return key in self._dict244+245+ def __iter__(self) -> typing.Iterator[typing.Any]:246+ return iter(self.keys())247+248+ def __len__(self) -> int:249+ return len(self._dict)250+251+ def __eq__(self, other: typing.Any) -> bool:252+ if not isinstance(other, self.__class__):253+ return False254+ return sorted(self._list) == sorted(other._list)255+256+ def __str__(self) -> str:257+ return urlencode(self._list)258+259+ def __repr__(self) -> str:260+ class_name = self.__class__.__name__261+ query_string = str(self)262+ return f"{class_name}({query_string!r})"263+264+265 class Headers(typing.MutableMapping[str, str]):266 """180- A case-insensitive multidict.267+ HTTP headers, as a case-insensitive multi-dict.268 """269 270 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:271 if headers is None:14 unmodified lines286 287 @property288 def encoding(self) -> str:289 """203- Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be204- seen in the wild.290+ Header encoding is mandated as ascii, but we allow fallbacks to utf-8291+ or iso-8859-1.292 """293 if self._encoding is None:294 for encoding in ["ascii", "utf-8"]:295 for key, value in self.raw:155 unmodified lines451 self,452 method: str,453 url: typing.Union[str, URL],454 *,455+ query_params: QueryParamTypes = None,456 headers: HeaderTypes = None,457 content: ByteOrByteStream = b"",458 ):459 self.method = method.upper()372- self.url = URL(url) if isinstance(url, str) else url460+ self.url = URL(url, query_params=query_params)461 if isinstance(content, bytes):462 self.is_streaming = False463 self.content = content464 else:278 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) == qmodified:tests/models/test_url.py+10 added
21 unmodified lines22 23 new = url.copy_with(scheme="http")24 assert new == URL("http://example.org:123/path/to/somewhere?abc=123#anchor")25 assert new.scheme == "http"26+27+28+def test_url_query_params():29+ url = URL("https://example.org:123/path/to/somewhere", query_params={"a": "123"})30+ assert str(url) == "https://example.org:123/path/to/somewhere?a=123"31+32+ url = URL(33+ "https://example.org:123/path/to/somewhere?b=456", query_params={"a": "123"}34+ )35+ assert str(url) == "https://example.org:123/path/to/somewhere?a=123"modified:README.md+8 added-8 removed
85 unmodified lines86 >>> response = await client.get('https://example.org')87 ```88 89 * `def __init__([ssl], [timeout], [pool_limits], [max_redirects])`90-* `async def .request(method, url, [content], [headers], [stream], [allow_redirects], [ssl], [timeout])`91-* `async def .get(url, [headers], [stream], [allow_redirects], [ssl], [timeout])`92-* `async def .options(url, [headers], [stream], [allow_redirects], [ssl], [timeout])`93-* `async def .head(url, [headers], [stream], [allow_redirects], [ssl], [timeout])`94-* `async def .post(url, [content], [headers], [stream], [allow_redirects], [ssl], [timeout])`95-* `async def .put(url, [content], [headers], [stream], [allow_redirects], [ssl], [timeout])`96-* `async def .patch(url, [content], [headers], [stream], [allow_redirects], [ssl], [timeout])`97-* `async def .delete(url, [content], [headers], [stream], [allow_redirects], [ssl], [timeout])`90+* `async def .request(method, url, [content], [query_params], [headers], [stream], [allow_redirects], [ssl], [timeout])`91+* `async def .get(url, [query_params], [headers], [stream], [allow_redirects], [ssl], [timeout])`92+* `async def .options(url, [query_params], [headers], [stream], [allow_redirects], [ssl], [timeout])`93+* `async def .head(url, [query_params], [headers], [stream], [allow_redirects], [ssl], [timeout])`94+* `async def .post(url, [content], [query_params], [headers], [stream], [allow_redirects], [ssl], [timeout])`95+* `async def .put(url, [content], [query_params], [headers], [stream], [allow_redirects], [ssl], [timeout])`96+* `async def .patch(url, [content], [query_params], [headers], [stream], [allow_redirects], [ssl], [timeout])`97+* `async def .delete(url, [content], [query_params], [headers], [stream], [allow_redirects], [ssl], [timeout])`98 * `def .prepare_request(request)`99 * `async def .send(request, [stream], [allow_redirects], [ssl], [timeout])`100 * `async def .close()`101 123 unmodified lines