Skip to content
Myr

Allow setting headers at the Client level (#159)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Stephen Brown II · committed by Seth Michael Larson · parent 3ba2e8c · Browse files · 4 files+142 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+142 added−1 removed

  • tests:+123 added−0 removed
  • other:+19 added−1 removed

4 files+142 added−1 removed

modified:docs/api.md+1 added-1 removed
modified:httpx/client.py+13 added
47 unmodified lines
48class BaseClient:49 def __init__(50 self,51 auth: AuthTypes = None,52 headers: HeaderTypes = None,53 cookies: CookieTypes = None,54 verify: VerifyTypes = True,55 cert: CertTypes = None,56 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
38 unmodified lines
95 else:96 self.base_url = URL(base_url)9798 self.auth = auth99 self.headers = Headers(headers)100 self.cookies = Cookies(cookies)101 self.max_redirects = max_redirects102 self.dispatch = async_dispatch103 self.concurrency_backend = backend
6 unmodified lines
110 merged_cookies.update(cookies)111 return merged_cookies112 return cookies113114 def merge_headers(115 self, headers: HeaderTypes = None116 ) -> typing.Optional[HeaderTypes]:117 if headers or self.headers:118 merged_headers = Headers(self.headers)119 merged_headers.update(headers)120 return merged_headers121 return headers122123 async def send(124 self,125 request: AsyncRequest,126 *,
410 unmodified lines
537 verify: VerifyTypes = None,538 timeout: TimeoutTypes = None,539 ) -> AsyncResponse:540 url = self.base_url.join(url)541 headers = self.merge_headers(headers)542 cookies = self.merge_cookies(cookies)543 request = AsyncRequest(544 method,545 url,
73 unmodified lines
619 verify: VerifyTypes = None,620 timeout: TimeoutTypes = None,621 ) -> Response:622 url = self.base_url.join(url)623 headers = self.merge_headers(headers)624 cookies = self.merge_cookies(cookies)625 request = AsyncRequest(626 method,627 url,
281 unmodified lines
modified:httpx/models.py+5 added
413 unmodified lines
414 for value in values:415 split_values.extend([item.strip() for item in value.split(",")])416 return split_values417418 def update(self, headers: HeaderTypes = None) -> None: # type: ignore419 headers = Headers(headers)420 for header in headers:421 self[header] = headers[header]422423 def __getitem__(self, key: str) -> str:424 """425 Return a single header value.426
757 unmodified lines
added:tests/client/test_headers.py+123 added
1#!/usr/bin/env python323import json4from httpx import (5 __version__,6 Client,7 AsyncRequest,8 AsyncResponse,9 VerifyTypes,10 CertTypes,11 TimeoutTypes,12 AsyncDispatcher,13)141516class 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_headers"):25 request_headers = dict(request.headers.items())26 body = json.dumps({"headers": request_headers}).encode()27 return AsyncResponse(200, content=body, request=request)282930def test_client_header():31 """32 Set a header in the Client.33 """34 url = "http://example.org/echo_headers"35 headers = {"Example-Header": "example-value"}3637 with Client(dispatch=MockDispatch(), headers=headers) as client:38 response = client.get(url)3940 assert response.status_code == 20041 assert response.json() == {42 "headers": {43 "accept": "*/*",44 "accept-encoding": "gzip, deflate, br",45 "connection": "keep-alive",46 "example-header": "example-value",47 "host": "example.org",48 "user-agent": f"python-httpx/{__version__}",49 }50 }515253def test_header_merge():54 url = "http://example.org/echo_headers"55 client_headers = {"User-Agent": "python-myclient/0.2.1"}56 request_headers = {"X-Auth-Token": "FooBarBazToken"}57 with Client(dispatch=MockDispatch(), headers=client_headers) as client:58 response = client.get(url, headers=request_headers)5960 assert response.status_code == 20061 assert response.json() == {62 "headers": {63 "accept": "*/*",64 "accept-encoding": "gzip, deflate, br",65 "connection": "keep-alive",66 "host": "example.org",67 "user-agent": "python-myclient/0.2.1",68 "x-auth-token": "FooBarBazToken",69 }70 }717273def test_header_merge_conflicting_headers():74 url = "http://example.org/echo_headers"75 client_headers = {"X-Auth-Token": "FooBar"}76 request_headers = {"X-Auth-Token": "BazToken"}77 with Client(dispatch=MockDispatch(), headers=client_headers) as client:78 response = client.get(url, headers=request_headers)7980 assert response.status_code == 20081 assert response.json() == {82 "headers": {83 "accept": "*/*",84 "accept-encoding": "gzip, deflate, br",85 "connection": "keep-alive",86 "host": "example.org",87 "user-agent": f"python-httpx/{__version__}",88 "x-auth-token": "BazToken",89 }90 }919293def test_header_update():94 url = "http://example.org/echo_headers"95 with Client(dispatch=MockDispatch()) as client:96 first_response = client.get(url)97 client.headers.update(98 {"User-Agent": "python-myclient/0.2.1", "Another-Header": "AThing"}99 )100 second_response = client.get(url)101102 assert first_response.status_code == 200103 assert first_response.json() == {104 "headers": {105 "accept": "*/*",106 "accept-encoding": "gzip, deflate, br",107 "connection": "keep-alive",108 "host": "example.org",109 "user-agent": f"python-httpx/{__version__}",110 }111 }112113 assert second_response.status_code == 200114 assert second_response.json() == {115 "headers": {116 "accept": "*/*",117 "accept-encoding": "gzip, deflate, br",118 "another-header": "AThing",119 "connection": "keep-alive",120 "host": "example.org",121 "user-agent": "python-myclient/0.2.1",122 }123 }