Adding params to Client (#372)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tyrel Souza · committed by Seth Michael Larson · parent b574230 · Browse files · 4 files·+102 added−1 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+102 added−1 removed
- tests:+51 added−0 removed
- other:+51 added−1 removed
Provenance
- Commit
5dc646f- Tree
8e8ea90- Author
Tyrel Souza <923113+tyrelsouza@users.noreply.github.com>- Committer
Seth Michael Larson <sethmichaellarson@gmail.com>- Parent
b574230
4 files changed+102 added−1 removed
modified:docs/api.md+2 added-1 removed
25 unmodified lines2627282930303132333435128 unmodified linesExpand all25 unmodified lines>>> client = httpx.Client()>>> response = client.get('https://example.org')```
* `def __init__([auth], [headers], [cookies], [verify], [cert], [timeout], [pool_limits], [max_redirects], [app], [dispatch])`* `def __init__([auth], [params], [headers], [cookies], [verify], [cert], [timeout], [pool_limits], [max_redirects], [app], [dispatch])`* `.params` - **QueryParams*** `.headers` - **Headers*** `.cookies` - **Cookies*** `def .get(url, [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout], [proxies])`* `def .options(url, [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout], [proxies])`128 unmodified linesExpand allmodified:httpx/client.py+24 added
38 unmodified lines39 CookieTypes,40 Headers,41 HeaderTypes,42 ProxiesTypes,43+ QueryParams,44 QueryParamTypes,45 RequestData,46 RequestFiles,47 Response,7 unmodified lines55 def __init__(56 self,57 *,58 auth: AuthTypes = None,59+ params: QueryParamTypes = None,60 headers: HeaderTypes = None,61 cookies: CookieTypes = None,62 verify: VerifyTypes = True,63 cert: CertTypes = None,49 unmodified lines113 self.proxies: typing.Dict[str, AsyncDispatcher] = _proxies_to_dispatchers(114 proxies115 )116 117+ if params is None:118+ params = {}119+120 self.auth = auth121+ self._params = QueryParams(params)122 self._headers = Headers(headers)123 self._cookies = Cookies(cookies)124 self.max_redirects = max_redirects125 self.dispatch = async_dispatch14 unmodified lines140 @cookies.setter141 def cookies(self, cookies: CookieTypes) -> None:142 self._cookies = Cookies(cookies)143 144+ @property145+ def params(self) -> QueryParams:146+ return self._params147+148+ @params.setter149+ def params(self, params: QueryParamTypes) -> None:150+ self._params = QueryParams(params)151+152 def check_concurrency_backend(self, backend: ConcurrencyBackend) -> None:153 pass # pragma: no cover154 155 def merge_url(self, url: URLTypes) -> URL:19 unmodified lines175 merged_headers.update(headers)176 return merged_headers177 return headers178 179+ def merge_queryparams(180+ self, params: QueryParamTypes = None181+ ) -> typing.Optional[QueryParamTypes]:182+ if params or self.params:183+ merged_queryparams = QueryParams(self.params)184+ merged_queryparams.update(params)185+ return merged_queryparams186+ return params187+188 async def _get_response(189 self,190 request: AsyncRequest,191 *,129 unmodified lines321 ) -> AsyncRequest:322 url = self.merge_url(url)323 headers = self.merge_headers(headers)324 cookies = self.merge_cookies(cookies)325+ params = self.merge_queryparams(params)326 request = AsyncRequest(327 method,328 url,329 data=data,771 unmodified linesmodified:httpx/models.py+25 added
314 unmodified lines315 if key in self._dict:316 return self._dict[key]317 return default318 319+ def update(self, params: QueryParamTypes = None) -> None: # type: ignore320+ if not params:321+ return322+323+ params = QueryParams(params)324+ for param in params:325+ self[param] = params[param]326+327 def __getitem__(self, key: typing.Any) -> str:328 return self._dict[key]329 330+ def __setitem__(self, key: str, value: str) -> None:331+ self._dict[key] = value332+333+ found_indexes = []334+ for idx, (item_key, _) in enumerate(self._list):335+ if item_key == key:336+ found_indexes.append(idx)337+338+ for idx in reversed(found_indexes[1:]):339+ del self._list[idx]340+341+ if found_indexes:342+ idx = found_indexes[0]343+ self._list[idx] = (key, value)344+ else:345+ self._list.append((key, value))346+347 def __contains__(self, key: typing.Any) -> bool:348 return key in self._dict349 350 def __iter__(self) -> typing.Iterator[typing.Any]:943 unmodified linesadded:tests/client/test_queryparams.py+51 added
1+import json2+3+from httpx import (4+ AsyncDispatcher,5+ AsyncRequest,6+ AsyncResponse,7+ CertTypes,8+ Client,9+ QueryParams,10+ TimeoutTypes,11+ VerifyTypes,12+)13+from httpx.models import URL14+15+16+class MockDispatch(AsyncDispatcher):17+ async def send(18+ self,19+ request: AsyncRequest,20+ verify: VerifyTypes = None,21+ cert: CertTypes = None,22+ timeout: TimeoutTypes = None,23+ ) -> AsyncResponse:24+ if request.url.path.startswith("/echo_queryparams"):25+ body = json.dumps({"ok": "ok"}).encode()26+ return AsyncResponse(200, content=body, request=request)27+28+29+def test_client_queryparams():30+ client = Client(params={"a": "b"})31+ assert isinstance(client.params, QueryParams)32+ assert client.params["a"] == "b"33+34+35+def test_client_queryparams_string():36+ client = Client(params="a=b")37+ assert isinstance(client.params, QueryParams)38+ assert client.params["a"] == "b"39+40+41+def test_client_queryparams_echo():42+ url = "http://example.org/echo_queryparams"43+ client_queryparams = "first=str"44+ request_queryparams = {"second": "dict"}45+ with Client(dispatch=MockDispatch(), params=client_queryparams) as client:46+ response = client.get(url, params=request_queryparams)47+48+ assert response.status_code == 20049+ assert response.url == URL(50+ "http://example.org/echo_queryparams?first=str&second=dict"51+ )