Add `build_request` to `Client` (#319)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Update documentation * Update documentation * Update tests Rename `_send` -> `_get_response` Update documentation * Code format with black * Change documentation example to OPTIONS * * Update documentation Small code reformat * `echo_headers` return json * Simplify test * Fix typo
authored by Dobrovolsky Bogdan · committed by Seth Michael Larson · parent 71648ec · Browse files · 6 files·+144 added−14 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+144 added−14 removed
- tests:+47 added−0 removed
- other:+97 added−14 removed
Provenance
- Commit
08edfac- Tree
95a39fc- Author
Dobrovolsky Bogdan <bogdan.gm24@gmail.com>- Committer
Seth Michael Larson <sethmichaellarson@gmail.com>- Parent
71648ec
6 files changed+144 added−14 removed
modified:docs/advanced.md+13 added
55 unmodified lines56575859606162636465666768697071727374757623 unmodified lines55 unmodified linesdispatch = httpx.WSGIDispatch(app=app, remote_addr="1.2.3.4")client = httpx.Client(dispatch=dispatch)```
## Build Request
You can use `Client.build_request()` to build a request andmake modifications before sending the request.
```python>>> client = httpx.Client()>>> req = client.build_request("OPTIONS", "https://example.com")>>> req.url.full_path = "*" # Build an 'OPTIONS *' request for CORS>>> client.send(r)<Response [200 OK]>```
## .netrc Support
HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter isnot defined, HTTPX tries to add auth into request's header from .netrc file.23 unmodified linesmodified:docs/api.md+2 added
14 unmodified lines15 * `put(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`16 * `patch(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`17 * `delete(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`18 * `request(method, url, [data], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`19+* `build_request(method, url, [data], [files], [json], [params], [headers], [cookies])`20 21 ## `Client`22 23 *An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.*13 unmodified lines37 * `def .put(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`38 * `def .patch(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`39 * `def .delete(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`40 * `def .request(method, url, [data], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`41+* `def .build_request(method, url, [data], [files], [json], [params], [headers], [cookies])`42 * `def .send(request, [stream], [allow_redirects], [verify], [cert], [timeout])`43 * `def .close()`44 45 ## `Response`112 unmodified linesmodified:httpx/client.py+82 added-14 removed
149 unmodified lines150 merged_headers.update(headers)151 return merged_headers152 return headers153 154- async def send(154+ async def _get_response(155 self,156 request: AsyncRequest,157 *,158 stream: bool = False,75 unmodified lines234 return BasicAuthMiddleware(username=username, password=password)235 236 return None237 238+ def build_request(239+ self,240+ method: str,241+ url: URLTypes,242+ *,243+ data: AsyncRequestData = None,244+ files: RequestFiles = None,245+ json: typing.Any = None,246+ params: QueryParamTypes = None,247+ headers: HeaderTypes = None,248+ cookies: CookieTypes = None,249+ ) -> AsyncRequest:250+ url = self.merge_url(url)251+ headers = self.merge_headers(headers)252+ cookies = self.merge_cookies(cookies)253+ request = AsyncRequest(254+ method,255+ url,256+ data=data,257+ files=files,258+ json=json,259+ params=params,260+ headers=headers,261+ cookies=cookies,262+ )263+ return request264 265+266 class AsyncClient(BaseClient):267 async def get(268 self,269 url: URLTypes,246 unmodified lines516 verify: VerifyTypes = None,517 timeout: TimeoutTypes = None,518 trust_env: bool = None,519 ) -> AsyncResponse:493- url = self.merge_url(url)494- headers = self.merge_headers(headers)495- cookies = self.merge_cookies(cookies)496- request = AsyncRequest(497- method,498- url,520+ request = self.build_request(521+ method=method,522+ url=url,523 data=data,524 files=files,525 json=json,526 params=params,11 unmodified lines538 trust_env=trust_env,539 )540 return response541 542+ async def send(543+ self,544+ request: AsyncRequest,545+ *,546+ stream: bool = False,547+ auth: AuthTypes = None,548+ allow_redirects: bool = True,549+ verify: VerifyTypes = None,550+ cert: CertTypes = None,551+ timeout: TimeoutTypes = None,552+ trust_env: bool = None,553+ ) -> AsyncResponse:554+ return await self._get_response(555+ request=request,556+ stream=stream,557+ auth=auth,558+ allow_redirects=allow_redirects,559+ verify=verify,560+ cert=cert,561+ timeout=timeout,562+ trust_env=trust_env,563+ )564+565 async def close(self) -> None:566 await self.dispatch.close()567 568 async def __aenter__(self) -> "AsyncClient":69 unmodified lines638 verify: VerifyTypes = None,639 timeout: TimeoutTypes = None,640 trust_env: bool = None,641 ) -> Response:595- url = self.merge_url(url)596- headers = self.merge_headers(headers)597- cookies = self.merge_cookies(cookies)598- request = AsyncRequest(599- method,600- url,642+ request = self.build_request(643+ method=method,644+ url=url,645 data=self._async_request_data(data),646 files=files,647 json=json,648 params=params,649 headers=headers,650 cookies=cookies,651 )652+ response = self.send(653+ request,654+ stream=stream,655+ auth=auth,656+ allow_redirects=allow_redirects,657+ verify=verify,658+ cert=cert,659+ timeout=timeout,660+ trust_env=trust_env,661+ )662+ return response663+664+ def send(665+ self,666+ request: AsyncRequest,667+ *,668+ stream: bool = False,669+ auth: AuthTypes = None,670+ allow_redirects: bool = True,671+ verify: VerifyTypes = None,672+ cert: CertTypes = None,673+ timeout: TimeoutTypes = None,674+ trust_env: bool = None,675+ ) -> Response:676 concurrency_backend = self.concurrency_backend677 610- coroutine = self.send678+ coroutine = self._get_response679 args = [request]680 kwargs = {681 "stream": True,682 "auth": auth,282 unmodified linesmodified:tests/client/test_async_client.py+14 added
12 unmodified lines13 assert response.headers14 assert repr(response) == "<Response [200 OK]>"15 16 17+async def test_build_request(server, backend):18+ url = server.url.copy_with(path="/echo_headers")19+ headers = {"Custom-header": "value"}20+ async with httpx.AsyncClient(backend=backend) as client:21+ request = client.build_request("GET", url)22+ request.headers.update(headers)23+ response = await client.send(request)24+25+ assert response.status_code == 20026+ assert response.url == url27+28+ assert response.json()["Custom-header"] == "value"29+30+31 @pytest.mark.asyncio32 async def test_get_no_backend(server):33 """34 Verify that the client is capable of making a simple request if not given a backend.111 unmodified linesmodified:tests/client/test_client.py+15 added
17 unmodified lines18 assert response.is_redirect is False19 assert repr(response) == "<Response [200 OK]>"20 21 22+def test_build_request(server):23+ url = server.url.copy_with(path="/echo_headers")24+ headers = {"Custom-header": "value"}25+26+ with httpx.Client() as http:27+ request = http.build_request("GET", url)28+ request.headers.update(headers)29+ response = http.send(request)30+31+ assert response.status_code == 20032+ assert response.url == url33+34+ assert response.json()["Custom-header"] == "value"35+36+37 def test_post(server):38 with httpx.Client() as http:39 response = http.post(server.url, data=b"Hello, world!")40 assert response.status_code == 200118 unmodified linesmodified:tests/conftest.py+18 added
1 import asyncio2+import json3 import os4 import threading5 import time6 import typing46 unmodified lines53 elif scope["path"].startswith("/status"):54 await status_code(scope, receive, send)55 elif scope["path"].startswith("/echo_body"):56 await echo_body(scope, receive, send)57+ elif scope["path"].startswith("/echo_headers"):58+ await echo_headers(scope, receive, send)59 else:60 await hello_world(scope, receive, send)61 62 50 unmodified lines113 )114 await send({"type": "http.response.body", "body": body})115 116 117+async def echo_headers(scope, receive, send):118+ body = {}119+ for name, value in scope.get("headers", []):120+ body[name.capitalize().decode()] = value.decode()121+122+ await send(123+ {124+ "type": "http.response.start",125+ "status": 200,126+ "headers": [[b"content-type", b"application/json"]],127+ }128+ )129+ await send({"type": "http.response.body", "body": json.dumps(body).encode()})130+131+132 class CAWithPKEncryption(trustme.CA):133 """Implementation of trustme.CA() that can emit134 private keys that are encrypted with a password.135 """132 unmodified lines