auth.py
This file
Path
httpcore/auth.py
38 lines · 1.1 KiB · Python
Last changed by
Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
History of this fileTake it
Auth (#65)Tom Christiebefore adoption5afa7dd
lines 1–3why, one step back1import typing2from base64 import b64encode3Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 4why, one step back4from .models import AsyncRequestAuth (#65)Tom Christiebefore adoption5afa7dd
lines 5–11why, one step back567class AuthBase:8 """9 Base class that all auth implementations derive from.10 """11Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 12why, one step back12 def __call__(self, request: AsyncRequest) -> AsyncRequest:Auth (#65)Tom Christiebefore adoption5afa7dd
lines 13–22why, one step back13 raise NotImplementedError("Auth hooks must be callable.") # pragma: nocover141516class HTTPBasicAuth(AuthBase):17 def __init__(18 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]19 ) -> None:20 self.username = username21 self.password = password22Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 23why, one step back23 def __call__(self, request: AsyncRequest) -> AsyncRequest:Auth (#65)Tom Christiebefore adoption5afa7dd
lines 24–38why, one step back24 request.headers["Authorization"] = self.build_auth_header()25 return request2627 def build_auth_header(self) -> str:28 username, password = self.username, self.password2930 if isinstance(username, str):31 username = username.encode("latin1")3233 if isinstance(password, str):34 password = password.encode("latin1")3536 userpass = b":".join((username, password))37 token = b64encode(userpass).decode().strip()38 return f"Basic {token}"