Skip to content
Myr

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

5 files+231 added−212 removed

deleted:httpx/auth.py-38 removed
1import typing2from base64 import b64encode34from .models import AsyncRequest567class AuthBase:8 """9 Base class that all auth implementations derive from.10 """1112 def __call__(self, request: AsyncRequest) -> AsyncRequest:13 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 = password2223 def __call__(self, request: AsyncRequest) -> AsyncRequest:24 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}"
modified:httpx/client.py+61 added-173 removed
1import functools2import inspect3import typing4from types import TracebackType56import hstspreload77from .auth import HTTPBasicAuth8from .concurrency.asyncio import AsyncioBackend9from .concurrency.base import ConcurrencyBackend10from .config import (11 DEFAULT_MAX_REDIRECTS,
9 unmodified lines
21from .dispatch.base import AsyncDispatcher, Dispatcher22from .dispatch.connection_pool import ConnectionPool23from .dispatch.threaded import ThreadedDispatcher24from .dispatch.wsgi import WSGIDispatch25from .exceptions import (26 HTTPError,27 InvalidURL,28 RedirectBodyUnavailable,29 RedirectLoop,30 TooManyRedirects,25from .exceptions import HTTPError, InvalidURL26from .middleware import (27 BaseMiddleware,28 BasicAuthMiddleware,29 CustomAuthMiddleware,30 RedirectMiddleware,31)32from .models import (33 URL,34 AsyncRequest,
11 unmodified lines
46 Response,47 ResponseContent,48 URLTypes,49)50from .status_codes import codes50from .utils import get_netrc_login515253class BaseClient:
11 unmodified lines
65 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 lines
164 cert: CertTypes = None,165 timeout: TimeoutTypes = None,166 trust_env: bool = None,167 ) -> AsyncResponse:169 if auth is None:170 auth = self.auth171172 url = request.url173174 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".')170177 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 )187188 if auth is not None:189 if isinstance(auth, tuple):190 auth = HTTPBasicAuth(username=auth[0], password=auth[1])191 request = auth(request)192193 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 raise205206 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 raise180212 return response213214 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 = []226227 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])234235 response = await self.dispatch.send(236 request, verify=verify, cert=cert, timeout=timeout237 )238239 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)245246 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()187255 if response.is_redirect:188 return response189257 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)194271 response.call_next = call_next # type: ignore195 get_response = wrap(196 get_response,197 RedirectMiddleware(allow_redirects=allow_redirects, cookies=self.cookies),198 )199273 return response274275 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 )205287 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)208294 # 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)210298 # 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])216303 # 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)219308 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 )226310 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 )231316 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)237318 # 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 None239323 # 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)240327 return url328329 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 headers339340 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.content351352241class AsyncClient(BaseClient):242 async def get(243 self,244 url: URLTypes,
654 unmodified lines
added:httpx/middleware.py+160 added
1import functools2import typing3from base64 import b64encode45from .config import DEFAULT_MAX_REDIRECTS6from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects7from .models import URL, AsyncRequest, AsyncResponse, Cookies, Headers8from .status_codes import codes91011class BaseMiddleware:12 async def __call__(13 self, request: AsyncRequest, get_response: typing.Callable14 ) -> AsyncResponse:15 raise NotImplementedError # pragma: no cover161718class 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")2425 if isinstance(password, str):26 password = password.encode("latin1")2728 userpass = b":".join((username, password))29 token = b64encode(userpass).decode().strip()3031 self.authorization_header = f"Basic {token}"3233 async def __call__(34 self, request: AsyncRequest, get_response: typing.Callable35 ) -> AsyncResponse:36 request.headers["Authorization"] = self.authorization_header37 return await get_response(request)383940class CustomAuthMiddleware(BaseMiddleware):41 def __init__(self, auth: typing.Callable[[AsyncRequest], AsyncRequest]):42 self.auth = auth4344 async def __call__(45 self, request: AsyncRequest, get_response: typing.Callable46 ) -> AsyncResponse:47 request = self.auth(request)48 return await get_response(request)495051class 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] = []6263 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()7071 response = await get_response(request)72 response.history = list(self.history)7374 if not response.is_redirect:75 return response7677 self.history.append(response)78 next_request = self.build_redirect_request(request, response)7980 if self.allow_redirects:81 return await self(next_request, get_response)8283 response.call_next = functools.partial(self, next_request, get_response)84 return response8586 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 )9899 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.method105106 # https://tools.ietf.org/html/rfc7231#section-6.4.4107 if response.status_code == codes.SEE_OTHER and method != "HEAD":108 method = "GET"109110 # 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"114115 # 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"119120 return method121122 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"]127128 url = URL(location, allow_relative=True)129130 # 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)134135 # 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)138139 return url140141 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 headers151152 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.content
modified:tests/client/test_auth.py+9 added
1import json2import os34import pytest56from httpx import (7 URL,8 AsyncDispatcher,9 AsyncRequest,
109 unmodified lines
119 with Client(dispatch=MockDispatch()) as client:120 response = client.get(url, auth=auth)121122 assert "'authorization': '[secure]'" in str(response.request.headers)123124125def 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 lines
261 with pytest.raises(RedirectBodyUnavailable):262 await client.post(url, data=streaming_body())263264265async def test_cross_dubdomain_redirect(backend):265async 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")