Refactor client functionality into middleware (#268)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Co-authored-by: yeraydiazdiaz <yeraydiazdiaz@gmail.com> * Dispatcher middlewares * Redirect and BasicAuth dispatchers * Remove HTTPBasicAuth and reinstate trust_env logic * Call resolve dispatcher correctly * Fix redirection tests * Add basic and custom auth dispatchers * Reinstate extracting cookies from response * Fix linting * Refactor middleware interface
authored by Florimond Manca · committed by GitHub · parent db7f2d0 · Browse files · 5 files·+231 added−212 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+231 added−212 removed
- tests:+10 added−1 removed
- other:+221 added−211 removed
Provenance
- Commit
40e6e8c- Tree
ac2257b- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
db7f2d0
5 files changed+231 added−212 removed
deleted:httpx/auth.py-38 removed
1-import typing2-from base64 import b64encode3-4-from .models import AsyncRequest5-6-7-class AuthBase:8- """9- Base class that all auth implementations derive from.10- """11-12- def __call__(self, request: AsyncRequest) -> AsyncRequest:13- raise NotImplementedError("Auth hooks must be callable.") # pragma: nocover14-15-16-class 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 = password22-23- def __call__(self, request: AsyncRequest) -> AsyncRequest:24- request.headers["Authorization"] = self.build_auth_header()25- return request26-27- def build_auth_header(self) -> str:28- username, password = self.username, self.password29-30- if isinstance(username, str):31- username = username.encode("latin1")32-33- if isinstance(password, str):34- password = password.encode("latin1")35-36- userpass = b":".join((username, password))37- token = b64encode(userpass).decode().strip()38- return f"Basic {token}"modified:httpx/client.py+61 added-173 removed
1+import functools2 import inspect3 import typing4 from types import TracebackType5 6 import hstspreload7 7-from .auth import HTTPBasicAuth8 from .concurrency.asyncio import AsyncioBackend9 from .concurrency.base import ConcurrencyBackend10 from .config import (11 DEFAULT_MAX_REDIRECTS,9 unmodified lines21 from .dispatch.base import AsyncDispatcher, Dispatcher22 from .dispatch.connection_pool import ConnectionPool23 from .dispatch.threaded import ThreadedDispatcher24 from .dispatch.wsgi import WSGIDispatch25-from .exceptions import (26- HTTPError,27- InvalidURL,28- RedirectBodyUnavailable,29- RedirectLoop,30- TooManyRedirects,25+from .exceptions import HTTPError, InvalidURL26+from .middleware import (27+ BaseMiddleware,28+ BasicAuthMiddleware,29+ CustomAuthMiddleware,30+ RedirectMiddleware,31 )32 from .models import (33 URL,34 AsyncRequest,11 unmodified lines46 Response,47 ResponseContent,48 URLTypes,49 )50-from .status_codes import codes50 from .utils import get_netrc_login51 52 53 class BaseClient:11 unmodified lines65 base_url: URLTypes = None,66 dispatch: typing.Union[AsyncDispatcher, Dispatcher] = None,67 app: typing.Callable = None,68 backend: ConcurrencyBackend = None,70- trust_env: bool = None,69+ trust_env: bool = True,70 ):71 if backend is None:72 backend = AsyncioBackend()73 90 unmodified lines164 cert: CertTypes = None,165 timeout: TimeoutTypes = None,166 trust_env: bool = None,167 ) -> AsyncResponse:169- if auth is None:170- auth = self.auth171-172- url = request.url173-174- if url.scheme not in ("http", "https"):168+ if request.url.scheme not in ("http", "https"):169 raise InvalidURL('URL scheme must be "http" or "https".')170 177- if auth is None:178- if url.username or url.password:179- auth = HTTPBasicAuth(username=url.username, password=url.password)180- elif self.trust_env if trust_env is None else trust_env:181- netrc_login = get_netrc_login(url.authority)182- if netrc_login:183- netrc_username, _, netrc_password = netrc_login184- auth = HTTPBasicAuth(185- username=netrc_username, password=netrc_password186- )187-188- if auth is not None:189- if isinstance(auth, tuple):190- auth = HTTPBasicAuth(username=auth[0], password=auth[1])191- request = auth(request)192-193- try:194- response = await self.send_handling_redirects(195- request,196- verify=verify,197- cert=cert,198- timeout=timeout,199- allow_redirects=allow_redirects,200- )201- except HTTPError as exc:202- # Add the original request to any HTTPError203- exc.request = request204- raise205-206- if not stream:171+ async def get_response(request: AsyncRequest) -> AsyncResponse:172 try:208- await response.read()209- finally:210- await response.close()173+ response = await self.dispatch.send(174+ request, verify=verify, cert=cert, timeout=timeout175+ )176+ except HTTPError as exc:177+ # Add the original request to any HTTPError178+ exc.request = request179+ raise180 212- return response213-214- async def send_handling_redirects(215- self,216- request: AsyncRequest,217- *,218- cert: CertTypes = None,219- verify: VerifyTypes = None,220- timeout: TimeoutTypes = None,221- allow_redirects: bool = True,222- history: typing.List[AsyncResponse] = None,223- ) -> AsyncResponse:224- if history is None:225- history = []226-227- while True:228- # We perform these checks here, so that calls to `response.next()`229- # will raise redirect errors if appropriate.230- if len(history) > self.max_redirects:231- raise TooManyRedirects(response=history[-1])232- if request.url in (response.url for response in history):233- raise RedirectLoop(response=history[-1])234-235- response = await self.dispatch.send(236- request, verify=verify, cert=cert, timeout=timeout237- )238-239- should_close_response = True240- try:241- assert isinstance(response, AsyncResponse)242- response.history = list(history)243- self.cookies.extract_cookies(response)244- history.append(response)245-246- if allow_redirects and response.is_redirect:247- request = self.build_redirect_request(request, response)248- else:249- should_close_response = False250- break251- finally:252- if should_close_response:181+ self.cookies.extract_cookies(response)182+ if not stream:183+ try:184+ await response.read()185+ finally:186 await response.close()187 255- if response.is_redirect:188+ return response189 257- async def call_next() -> AsyncResponse:258- nonlocal request, response, verify, cert259- nonlocal allow_redirects, timeout, history260- request = self.build_redirect_request(request, response)261- response = await self.send_handling_redirects(262- request,263- allow_redirects=allow_redirects,264- verify=verify,265- cert=cert,266- timeout=timeout,267- history=history,268- )269- return response190+ def wrap(191+ get_response: typing.Callable, middleware: BaseMiddleware192+ ) -> typing.Callable:193+ return functools.partial(middleware, get_response=get_response)194 271- response.call_next = call_next # type: ignore195+ get_response = wrap(196+ get_response,197+ RedirectMiddleware(allow_redirects=allow_redirects, cookies=self.cookies),198+ )199 273- return response274-275- def build_redirect_request(276- self, request: AsyncRequest, response: AsyncResponse277- ) -> AsyncRequest:278- method = self.redirect_method(request, response)279- url = self.redirect_url(request, response)280- headers = self.redirect_headers(request, url)281- content = self.redirect_content(request, method, response)282- cookies = self.merge_cookies(request.cookies)283- return AsyncRequest(284- method=method, url=url, headers=headers, data=content, cookies=cookies200+ auth_middleware = self._get_auth_middleware(201+ request=request,202+ trust_env=self.trust_env if trust_env is None else trust_env,203+ auth=self.auth if auth is None else auth,204 )205 287- def redirect_method(self, request: AsyncRequest, response: AsyncResponse) -> str:288- """289- When being redirected we may want to change the method of the request290- based on certain specs or browser behavior.291- """292- method = request.method206+ if auth_middleware is not None:207+ get_response = wrap(get_response, auth_middleware)208 294- # https://tools.ietf.org/html/rfc7231#section-6.4.4295- if response.status_code == codes.SEE_OTHER and method != "HEAD":296- method = "GET"209+ return await get_response(request)210 298- # Do what the browsers do, despite standards...299- # Turn 302s into GETs.300- if response.status_code == codes.FOUND and method != "HEAD":301- method = "GET"211+ def _get_auth_middleware(212+ self, request: AsyncRequest, trust_env: bool, auth: AuthTypes = None213+ ) -> typing.Optional[BaseMiddleware]:214+ if isinstance(auth, tuple):215+ return BasicAuthMiddleware(username=auth[0], password=auth[1])216 303- # If a POST is responded to with a 301, turn it into a GET.304- # This bizarre behaviour is explained in 'requests' issue 1704.305- if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":306- method = "GET"217+ if callable(auth):218+ return CustomAuthMiddleware(auth=auth)219 308- return method220+ if auth is not None:221+ raise TypeError(222+ 'When specified, "auth" must be a (username, password) tuple or '223+ "a callable with signature (AsyncRequest) -> AsyncRequest "224+ f"(got {auth!r})"225+ )226 310- def redirect_url(self, request: AsyncRequest, response: AsyncResponse) -> URL:311- """312- Return the URL for the redirect to follow.313- """314- location = response.headers["Location"]227+ if request.url.username or request.url.password:228+ return BasicAuthMiddleware(229+ username=request.url.username, password=request.url.password230+ )231 316- url = URL(location, allow_relative=True)232+ if trust_env:233+ netrc_login = get_netrc_login(request.url.authority)234+ if netrc_login:235+ username, _, password = netrc_login236+ return BasicAuthMiddleware(username=username, password=password)237 318- # Facilitate relative 'Location' headers, as allowed by RFC 7231.319- # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')320- if url.is_relative_url:321- url = request.url.join(url)238+ return None239 323- # Attach previous fragment if needed (RFC 7231 7.1.2)324- if request.url.fragment and not url.fragment:325- url = url.copy_with(fragment=request.url.fragment)240 327- return url328-329- def redirect_headers(self, request: AsyncRequest, url: URL) -> Headers:330- """331- Strip Authorization headers when responses are redirected away from332- the origin.333- """334- headers = Headers(request.headers)335- if url.origin != request.url.origin:336- del headers["Authorization"]337- del headers["host"]338- return headers339-340- def redirect_content(341- self, request: AsyncRequest, method: str, response: AsyncResponse342- ) -> bytes:343- """344- Return the body that should be used for the redirect request.345- """346- if method != request.method and method == "GET":347- return b""348- if request.is_streaming:349- raise RedirectBodyUnavailable(response=response)350- return request.content351-352-241 class AsyncClient(BaseClient):242 async def get(243 self,244 url: URLTypes,654 unmodified linesadded:httpx/middleware.py+160 added
1+import functools2+import typing3+from base64 import b64encode4+5+from .config import DEFAULT_MAX_REDIRECTS6+from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects7+from .models import URL, AsyncRequest, AsyncResponse, Cookies, Headers8+from .status_codes import codes9+10+11+class BaseMiddleware:12+ async def __call__(13+ self, request: AsyncRequest, get_response: typing.Callable14+ ) -> AsyncResponse:15+ raise NotImplementedError # pragma: no cover16+17+18+class BasicAuthMiddleware(BaseMiddleware):19+ def __init__(20+ self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]21+ ):22+ if isinstance(username, str):23+ username = username.encode("latin1")24+25+ if isinstance(password, str):26+ password = password.encode("latin1")27+28+ userpass = b":".join((username, password))29+ token = b64encode(userpass).decode().strip()30+31+ self.authorization_header = f"Basic {token}"32+33+ async def __call__(34+ self, request: AsyncRequest, get_response: typing.Callable35+ ) -> AsyncResponse:36+ request.headers["Authorization"] = self.authorization_header37+ return await get_response(request)38+39+40+class CustomAuthMiddleware(BaseMiddleware):41+ def __init__(self, auth: typing.Callable[[AsyncRequest], AsyncRequest]):42+ self.auth = auth43+44+ async def __call__(45+ self, request: AsyncRequest, get_response: typing.Callable46+ ) -> AsyncResponse:47+ request = self.auth(request)48+ return await get_response(request)49+50+51+class RedirectMiddleware(BaseMiddleware):52+ def __init__(53+ self,54+ allow_redirects: bool = True,55+ max_redirects: int = DEFAULT_MAX_REDIRECTS,56+ cookies: typing.Optional[Cookies] = None,57+ ):58+ self.allow_redirects = allow_redirects59+ self.max_redirects = max_redirects60+ self.cookies = cookies61+ self.history: typing.List[AsyncResponse] = []62+63+ async def __call__(64+ self, request: AsyncRequest, get_response: typing.Callable65+ ) -> AsyncResponse:66+ if len(self.history) > self.max_redirects:67+ raise TooManyRedirects()68+ if request.url in (response.url for response in self.history):69+ raise RedirectLoop()70+71+ response = await get_response(request)72+ response.history = list(self.history)73+74+ if not response.is_redirect:75+ return response76+77+ self.history.append(response)78+ next_request = self.build_redirect_request(request, response)79+80+ if self.allow_redirects:81+ return await self(next_request, get_response)82+83+ response.call_next = functools.partial(self, next_request, get_response)84+ return response85+86+ def build_redirect_request(87+ self, request: AsyncRequest, response: AsyncResponse88+ ) -> AsyncRequest:89+ method = self.redirect_method(request, response)90+ url = self.redirect_url(request, response)91+ headers = self.redirect_headers(request, url) # TODO: merge headers?92+ content = self.redirect_content(request, method)93+ cookies = Cookies(self.cookies)94+ cookies.update(request.cookies)95+ return AsyncRequest(96+ method=method, url=url, headers=headers, data=content, cookies=cookies97+ )98+99+ def redirect_method(self, request: AsyncRequest, response: AsyncResponse) -> str:100+ """101+ When being redirected we may want to change the method of the request102+ based on certain specs or browser behavior.103+ """104+ method = request.method105+106+ # https://tools.ietf.org/html/rfc7231#section-6.4.4107+ if response.status_code == codes.SEE_OTHER and method != "HEAD":108+ method = "GET"109+110+ # Do what the browsers do, despite standards...111+ # Turn 302s into GETs.112+ if response.status_code == codes.FOUND and method != "HEAD":113+ method = "GET"114+115+ # If a POST is responded to with a 301, turn it into a GET.116+ # This bizarre behaviour is explained in 'requests' issue 1704.117+ if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":118+ method = "GET"119+120+ return method121+122+ def redirect_url(self, request: AsyncRequest, response: AsyncResponse) -> URL:123+ """124+ Return the URL for the redirect to follow.125+ """126+ location = response.headers["Location"]127+128+ url = URL(location, allow_relative=True)129+130+ # Facilitate relative 'Location' headers, as allowed by RFC 7231.131+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')132+ if url.is_relative_url:133+ url = request.url.join(url)134+135+ # Attach previous fragment if needed (RFC 7231 7.1.2)136+ if request.url.fragment and not url.fragment:137+ url = url.copy_with(fragment=request.url.fragment)138+139+ return url140+141+ def redirect_headers(self, request: AsyncRequest, url: URL) -> Headers:142+ """143+ Strip Authorization headers when responses are redirected away from144+ the origin.145+ """146+ headers = Headers(request.headers)147+ if url.origin != request.url.origin:148+ del headers["Authorization"]149+ del headers["host"]150+ return headers151+152+ def redirect_content(self, request: AsyncRequest, method: str) -> bytes:153+ """154+ Return the body that should be used for the redirect request.155+ """156+ if method != request.method and method == "GET":157+ return b""158+ if request.is_streaming:159+ raise RedirectBodyUnavailable()160+ return request.contentmodified:tests/client/test_auth.py+9 added
1 import json2 import os3 4+import pytest5+6 from httpx import (7 URL,8 AsyncDispatcher,9 AsyncRequest,109 unmodified lines119 with Client(dispatch=MockDispatch()) as client:120 response = client.get(url, auth=auth)121 122 assert "'authorization': '[secure]'" in str(response.request.headers)123+124+125+def test_auth_invalid_type():126+ url = "https://example.org/"127+ with Client(dispatch=MockDispatch(), auth="not a tuple, not a callable") as client:128+ with pytest.raises(TypeError):129+ client.get(url)modified:tests/client/test_redirects.py+1 added-1 removed
260 unmodified lines261 with pytest.raises(RedirectBodyUnavailable):262 await client.post(url, data=streaming_body())263 264 265-async def test_cross_dubdomain_redirect(backend):265+async def test_cross_subdomain_redirect(backend):266 client = AsyncClient(dispatch=MockDispatch(), backend=backend)267 url = "https://example.com/cross_subdomain"268 response = await client.get(url)269 assert response.url == URL("https://www.example.org/cross_subdomain")