Skip to content
Myr

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

7 files+179 added−22 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/client.py+27 added-2 removed
13 unmodified lines
14 SSLConfig,15 TimeoutConfig,16)17from .dispatch.connection_pool import ConnectionPool18from .models import URL, ByteOrByteStream, HeaderTypes, Request, Response, URLTypes18from .models import (19 URL,20 ByteOrByteStream,21 HeaderTypes,22 QueryParamTypes,23 Request,24 Response,25 URLTypes,26)272829class Client:30 def __init__(
18 unmodified lines
49 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 lines
73 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 line
83 ) -> 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 lines
95 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 line
105 ) -> 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 lines
117 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 line
127 ) -> 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 lines
140 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 lines
151 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 lines
164 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 lines
175 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 lines
188 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 lines
199 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 lines
212 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 lines
223 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 lines
modified:httpcore/models.py+93 added-5 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,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 lines
6970 # Normalize scheme and domain name.71 self.components = self.components.normalize()7273 # 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)7778 # 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 lines
173 return f"{class_name}({url_str!r})"174175176class Origin:177 """178 The URL scheme and authority information, as a comparable, hashable object.179 """180181 def __init__(self, url: URLTypes) -> None:182 if not isinstance(url, URL):183 url = URL(url)184 self.is_ssl = url.is_ssl
11 unmodified lines
196 def __hash__(self) -> int:197 return hash((self.is_ssl, self.host, self.port))198199200class 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."204205 value = args[0] if args else kwargs206207 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: ignore215216 self._list = [(str(k), str(v)) for k, v in items]217 self._dict = {str(k): str(v) for k, v in items}218219 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]221222 def keys(self) -> typing.KeysView:223 return self._dict.keys()224225 def values(self) -> typing.ValuesView:226 return self._dict.values()227228 def items(self) -> typing.ItemsView:229 return self._dict.items()230231 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:232 return list(self._list)233234 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 default238239 def __getitem__(self, key: typing.Any) -> str:240 return self._dict[key]241242 def __contains__(self, key: typing.Any) -> bool:243 return key in self._dict244245 def __iter__(self) -> typing.Iterator[typing.Any]:246 return iter(self.keys())247248 def __len__(self) -> int:249 return len(self._dict)250251 def __eq__(self, other: typing.Any) -> bool:252 if not isinstance(other, self.__class__):253 return False254 return sorted(self._list) == sorted(other._list)255256 def __str__(self) -> str:257 return urlencode(self._list)258259 def __repr__(self) -> str:260 class_name = self.__class__.__name__261 query_string = str(self)262 return f"{class_name}({query_string!r})"263264265class Headers(typing.MutableMapping[str, str]):266 """180 A case-insensitive multidict.267 HTTP headers, as a case-insensitive multi-dict.268 """269270 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:271 if headers is None:
14 unmodified lines
286287 @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 lines
451 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 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
modified:tests/models/test_url.py+10 added
21 unmodified lines
2223 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"262728def 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"3132 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 lines
86>>> response = await client.get('https://example.org')87```8889* `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