Add `Client.auth` setter (#1185)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Florimond Manca · committed by GitHub · parent 34ba0e1 · Browse files · 3 files·+62 added−20 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+62 added−20 removed
- tests:+27 added−6 removed
- other:+35 added−14 removed
Provenance
- Commit
cb620e6- Tree
ed3c905- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
34ba0e1
3 files changed+62 added−20 removed
modified:docs/api.md+2 added-2 removed
34 unmodified lines3536373839394041424344454546474849108 unmodified linesExpand all34 unmodified lines## `Client`
::: httpx.Client :docstring: :members: headers cookies params request get head options post put patch delete build_request send close :members: headers cookies params auth request get head options post put patch delete build_request send close
## `AsyncClient`
::: httpx.AsyncClient :docstring: :members: headers cookies params request get head options post put patch delete build_request send aclose :members: headers cookies params auth request get head options post put patch delete build_request send aclose
## `Response`
108 unmodified linesExpand allmodified:httpx/_client.py+33 added-12 removed
69 unmodified lines70 trust_env: bool = True,71 ):72 self._base_url = self._enforce_trailing_slash(URL(base_url))73 74- self.auth = auth74+ self._auth = self._build_auth(auth)75 self._params = QueryParams(params)76 self._headers = Headers(headers)77 self._cookies = Cookies(cookies)78 self._timeout = Timeout(timeout)38 unmodified lines117 def timeout(self, timeout: TimeoutTypes) -> None:118 self._timeout = Timeout(timeout)119 120 @property121+ def auth(self) -> typing.Optional[Auth]:122+ """123+ Authentication class used when none is passed at the request-level.124+125+ See also [Authentication][0].126+127+ [0]: /quickstart/#authentication128+ """129+ return self._auth130+131+ @auth.setter132+ def auth(self, auth: AuthTypes) -> None:133+ self._auth = self._build_auth(auth)134+135+ @property136 def base_url(self) -> URL:137 """138 Base URL to use when sending requests with relative URLs.139 """158 unmodified lines298 merged_queryparams.update(params)299 return merged_queryparams300 return params301 287- def _build_auth(302+ def _build_auth(self, auth: AuthTypes) -> typing.Optional[Auth]:303+ if auth is None:304+ return None305+ elif isinstance(auth, tuple):306+ return BasicAuth(username=auth[0], password=auth[1])307+ elif isinstance(auth, Auth):308+ return auth309+ elif callable(auth):310+ return FunctionAuth(func=auth)311+ else:312+ raise TypeError('Invalid "auth" argument.')313+314+ def _build_request_auth(315 self, request: Request, auth: typing.Union[AuthTypes, UnsetType] = UNSET316 ) -> Auth:290- auth = self.auth if isinstance(auth, UnsetType) else auth317+ auth = self._auth if isinstance(auth, UnsetType) else self._build_auth(auth)318 319 if auth is not None:293- if isinstance(auth, tuple):294- return BasicAuth(username=auth[0], password=auth[1])295- elif isinstance(auth, Auth):296- return auth320+ return auth297- elif callable(auth):298- return FunctionAuth(func=auth)299- raise TypeError('Invalid "auth" argument.')321 322 username, password = request.url.username, request.url.password323 if username or password:324 return BasicAuth(username=username, password=password)362 unmodified lines687 [0]: /advanced/#request-instances688 """689 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)690 670- auth = self._build_auth(request, auth)691+ auth = self._build_request_auth(request, auth)692 693 response = self._send_handling_redirects(694 request, auth=auth, timeout=timeout, allow_redirects=allow_redirects,695 )593 unmodified lines1289 [0]: /advanced/#request-instances1290 """1291 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)1292 1272- auth = self._build_auth(request, auth)1293+ auth = self._build_request_auth(request, auth)1294 1295 response = await self._send_handling_redirects(1296 request, auth=auth, timeout=timeout, allow_redirects=allow_redirects,1297 )404 unmodified linesmodified:tests/client/test_auth.py+27 added-6 removed
7 unmodified lines8 from httpx import (9 URL,10 AsyncClient,11 Auth,12+ BasicAuth,13 Client,14 DigestAuth,15 ProtocolError,16 Request,293 unmodified lines310 assert "'authorization': '[secure]'" in str(response.request.headers)311 312 313 @pytest.mark.asyncio313-async def test_auth_invalid_type() -> None:314+async def test_auth_property() -> None:315+ client = AsyncClient(transport=AsyncMockTransport())316+ assert client.auth is None317+318+ client.auth = ("tomchristie", "password123") # type: ignore319+ assert isinstance(client.auth, BasicAuth)320+321 url = "https://example.org/"315- client = AsyncClient(316- transport=AsyncMockTransport(),317- auth="not a tuple, not a callable", # type: ignore318- )322+ response = await client.get(url)323+ assert response.status_code == 200324+ assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}325+326+327+@pytest.mark.asyncio328+async def test_auth_invalid_type() -> None:329 with pytest.raises(TypeError):320- await client.get(url)330+ client = AsyncClient(331+ transport=AsyncMockTransport(),332+ auth="not a tuple, not a callable", # type: ignore333+ )334 335+ client = AsyncClient(transport=AsyncMockTransport())336 337+ with pytest.raises(TypeError):338+ await client.get(auth="not a tuple, not a callable") # type: ignore339+340+ with pytest.raises(TypeError):341+ client.auth = "not a tuple, not a callable" # type: ignore342+343+344 @pytest.mark.asyncio345 async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:346 url = "https://example.org/"347 auth = DigestAuth(username="tomchristie", password="password123")296 unmodified lines