Prep for introducing SyncClient (#713)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Reorganize method ordering in client * Move 'request' * Use 'httpx.Proxy' for proxy configuration
authored by Tom Christie · committed by GitHub · parent e1afbfa · Browse files · 7 files·+339 added−234 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+339 added−234 removed
- tests:+17 added−2 removed
- other:+322 added−232 removed
Provenance
- Commit
f17ab37- Tree
7e1cf54- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
e1afbfa
7 files changed+339 added−234 removed
modified:httpx/__init__.py+2 added-1 removed
1 unmodified line2 from .api import delete, get, head, options, patch, post, put, request, stream3 from .auth import BasicAuth, DigestAuth4 from .client import AsyncClient, Client5 from .config import TimeoutConfig # For 0.8 backwards compat.6-from .config import PoolLimits, Timeout6+from .config import PoolLimits, Proxy, Timeout7 from .dispatch.proxy_http import HTTPProxy, HTTPProxyMode8 from .exceptions import (9 ConnectionClosed,10 ConnectTimeout,37 unmodified lines48 "BasicAuth",49 "Client",50 "DigestAuth",51 "PoolLimits",52+ "Proxy",53 "Timeout",54 "TimeoutConfig", # For 0.8 backwards compat.55 "HTTPProxy",56 "HTTPProxyMode", # For 0.8 backwards compat.29 unmodified linesmodified:httpx/client.py+285 added-215 removed
12 unmodified lines13 DEFAULT_TIMEOUT_CONFIG,14 UNSET,15 CertTypes,16 PoolLimits,17+ ProxiesTypes,18+ Proxy,19 Timeout,20 TimeoutTypes,21 UnsetType,22 VerifyTypes,15 unmodified lines38 Cookies,39 CookieTypes,40 Headers,41 HeaderTypes,40- ProxiesTypes,42 QueryParams,43 QueryParamTypes,44 Request,45 RequestData,80 unmodified lines126 backend: typing.Union[str, ConcurrencyBackend] = "auto",127 trust_env: bool = True,128 uds: str = None,129 ):129- if app is not None:130- dispatch = ASGIDispatch(app=app)131-132- if dispatch is None:133- dispatch = ConnectionPool(134- verify=verify,135- cert=cert,136- http2=http2,137- pool_limits=pool_limits,138- backend=backend,139- trust_env=trust_env,140- uds=uds,141- )142-130 if base_url is None:131 self.base_url = URL("", allow_relative=True)132 else:133 self.base_url = URL(base_url)134 135 if params is None:136 params = {}137 138+ if proxies is None and trust_env:139+ proxies = typing.cast(ProxiesTypes, get_environment_proxies())140+141 self.auth = auth142 self._params = QueryParams(params)143 self._headers = Headers(headers)144 self._cookies = Cookies(cookies)145 self.timeout = Timeout(timeout)146 self.max_redirects = max_redirects147 self.trust_env = trust_env158- self.dispatch = dispatch148 self.netrc = NetRCInfo()149 150+ self.dispatch = self.init_dispatch(151+ verify=verify,152+ cert=cert,153+ http2=http2,154+ pool_limits=pool_limits,155+ dispatch=dispatch,156+ app=app,157+ backend=backend,158+ trust_env=trust_env,159+ uds=uds,160+ )161+162 if proxies is None and trust_env:163 proxies = typing.cast(ProxiesTypes, get_environment_proxies())164 164- self.proxies: typing.Dict[str, AsyncDispatcher] = _proxies_to_dispatchers(165+ self.proxies: typing.Dict[str, AsyncDispatcher] = self.proxies_to_dispatchers(166 proxies,167 verify=verify,168 cert=cert,169 http2=http2,1 unmodified line171 backend=backend,172 trust_env=trust_env,173 )174 175+ def init_dispatch(176+ self,177+ verify: VerifyTypes = True,178+ cert: CertTypes = None,179+ http2: bool = False,180+ pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,181+ dispatch: AsyncDispatcher = None,182+ app: typing.Callable = None,183+ backend: typing.Union[str, ConcurrencyBackend] = "auto",184+ trust_env: bool = True,185+ uds: str = None,186+ ) -> AsyncDispatcher:187+ if dispatch is not None:188+ return dispatch189+190+ if app is not None:191+ return ASGIDispatch(app=app)192+193+ return ConnectionPool(194+ verify=verify,195+ cert=cert,196+ http2=http2,197+ pool_limits=pool_limits,198+ backend=backend,199+ trust_env=trust_env,200+ uds=uds,201+ )202+203+ def init_proxy_dispatch(204+ self,205+ proxy: Proxy,206+ verify: VerifyTypes = True,207+ cert: CertTypes = None,208+ http2: bool = False,209+ pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,210+ backend: typing.Union[str, ConcurrencyBackend] = "auto",211+ trust_env: bool = True,212+ ) -> AsyncDispatcher:213+ return HTTPProxy(214+ proxy_url=proxy.url,215+ proxy_headers=proxy.headers,216+ proxy_mode=proxy.mode,217+ verify=verify,218+ cert=cert,219+ http2=http2,220+ pool_limits=pool_limits,221+ backend=backend,222+ trust_env=trust_env,223+ )224+225+ def proxies_to_dispatchers(226+ self,227+ proxies: typing.Optional[ProxiesTypes],228+ verify: VerifyTypes,229+ cert: typing.Optional[CertTypes],230+ http2: bool,231+ pool_limits: PoolLimits,232+ backend: typing.Union[str, ConcurrencyBackend],233+ trust_env: bool,234+ ) -> typing.Dict[str, AsyncDispatcher]:235+ if proxies is None:236+ return {}237+ elif isinstance(proxies, (str, URL, Proxy)):238+ proxy = Proxy(url=proxies) if isinstance(proxies, (str, URL)) else proxies239+ return {240+ "all": self.init_proxy_dispatch(241+ proxy=proxy,242+ verify=verify,243+ cert=cert,244+ pool_limits=pool_limits,245+ backend=backend,246+ trust_env=trust_env,247+ http2=http2,248+ )249+ }250+ elif isinstance(proxies, AsyncDispatcher): # pragma: nocover251+ return {"all": proxies}252+ # We're supporting this style for now, but we'll want to deprecate it.253+ #254+ # raise RuntimeError(255+ # "Passing a AsyncDispatcher instance to 'proxies=' is no longer256+ # supported. Use `httpx.Proxy() instead.`"257+ # )258+ else:259+ new_proxies = {}260+ for key, value in proxies.items():261+ if isinstance(value, (str, URL, Proxy)):262+ proxy = Proxy(url=value) if isinstance(value, (str, URL)) else value263+ new_proxies[str(key)] = self.init_proxy_dispatch(264+ proxy=proxy,265+ verify=verify,266+ cert=cert,267+ pool_limits=pool_limits,268+ backend=backend,269+ trust_env=trust_env,270+ http2=http2,271+ )272+ elif isinstance(value, AsyncDispatcher): # pragma: nocover273+ new_proxies[str(key)] = value274+ # We're supporting this style for now, but we'll want to275+ # deprecate it.276+ #277+ # raise RuntimeError(278+ # "Passing a AsyncDispatcher instance to 'proxies=' is "279+ # "no longer supported. Use `httpx.Proxy() instead.`"280+ # )281+ return new_proxies282+283 @property284 def headers(self) -> Headers:285 """286 HTTP headers to include when sending requests.25 unmodified lines312 @params.setter313 def params(self, params: QueryParamTypes) -> None:314 self._params = QueryParams(params)315 207- async def request(208- self,209- method: str,210- url: URLTypes,211- *,212- data: RequestData = None,213- files: RequestFiles = None,214- json: typing.Any = None,215- params: QueryParamTypes = None,216- headers: HeaderTypes = None,217- cookies: CookieTypes = None,218- stream: bool = False,219- auth: AuthTypes = None,220- allow_redirects: bool = True,221- cert: CertTypes = None,222- verify: VerifyTypes = None,223- timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,224- trust_env: bool = None,225- ) -> Response:226- if cert is not None: # pragma: nocover227- raise RuntimeError(228- "Passing a 'cert' argument when making a request on a client "229- "is not supported anymore. Instantiate a new client instead, "230- "passing any 'cert' arguments to the client itself."231- )232-233- if verify is not None: # pragma: nocover234- raise RuntimeError(235- "Passing a 'verify' argument when making a request on a client "236- "is not supported anymore. Instantiate a new client instead, "237- "passing any 'verify' arguments to the client itself."238- )239-240- if trust_env is not None: # pragma: nocover241- raise RuntimeError(242- "Passing a 'trust_env' argument when making a request on a client "243- "is not supported anymore. Instantiate a new client instead, "244- "passing any 'trust_env' argument to the client itself."245- )246-247- if stream: # pragma: nocover248- warnings.warn(249- "The 'stream=True' argument is due to be deprecated. "250- "Use 'async with client.stream(method, url, ...) as response' instead."251- )252-253- request = self.build_request(254- method=method,255- url=url,256- data=data,257- files=files,258- json=json,259- params=params,260- headers=headers,261- cookies=cookies,262- )263- response = await self.send(264- request,265- stream=stream,266- auth=auth,267- allow_redirects=allow_redirects,268- timeout=timeout,269- )270- return response271-316 def stream(317 self,318 method: str,319 url: URLTypes,105 unmodified lines425 merged_queryparams.update(params)426 return merged_queryparams427 return params428 385- async def send(386- self,387- request: Request,388- *,389- stream: bool = False,390- auth: AuthTypes = None,391- allow_redirects: bool = True,392- timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,393- ) -> Response:394- if request.url.scheme not in ("http", "https"):395- raise InvalidURL('URL scheme must be "http" or "https".')396-397- timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)398-399- auth = self.setup_auth(request, auth)400-401- response = await self.send_handling_redirects(402- request, auth=auth, timeout=timeout, allow_redirects=allow_redirects,403- )404-405- if not stream:406- try:407- await response.aread()408- finally:409- await response.aclose()410-411- return response412-413- def setup_auth(self, request: Request, auth: AuthTypes = None) -> Auth:429+ def build_auth(self, request: Request, auth: AuthTypes = None) -> Auth:430 auth = self.auth if auth is None else auth431 432 if auth is not None:433 if isinstance(auth, tuple):14 unmodified lines448 return BasicAuth(username=credentials[0], password=credentials[1])449 450 return Auth()451 436- async def send_handling_redirects(437- self,438- request: Request,439- auth: Auth,440- timeout: Timeout,441- allow_redirects: bool = True,442- history: typing.List[Response] = None,443- ) -> Response:444- if history is None:445- history = []446-447- while True:448- if len(history) > self.max_redirects:449- raise TooManyRedirects()450- if request.url in (response.url for response in history):451- raise RedirectLoop()452-453- response = await self.send_handling_auth(454- request, history, auth=auth, timeout=timeout,455- )456- response.history = list(history)457-458- if not response.is_redirect:459- return response460-461- await response.aread()462- request = self.build_redirect_request(request, response)463- history = history + [response]464-465- if not allow_redirects:466- response.call_next = functools.partial(467- self.send_handling_redirects,468- request=request,469- auth=auth,470- timeout=timeout,471- allow_redirects=False,472- history=history,473- )474- return response475-452 def build_redirect_request(self, request: Request, response: Response) -> Request:453 """454 Given a request and a redirect response, return a new request that455 should be used to effect the redirect.89 unmodified lines545 )546 547 return request.stream548 549+ def dispatcher_for_url(self, url: URL) -> AsyncDispatcher:550+ """551+ Returns the AsyncDispatcher instance that should be used for a given URL.552+ This will either be the standard connection pool, or a proxy.553+ """554+ if self.proxies:555+ is_default_port = (url.scheme == "http" and url.port == 80) or (556+ url.scheme == "https" and url.port == 443557+ )558+ hostname = f"{url.host}:{url.port}"559+ proxy_keys = (560+ f"{url.scheme}://{hostname}",561+ f"{url.scheme}://{url.host}" if is_default_port else None,562+ f"all://{hostname}",563+ f"all://{url.host}" if is_default_port else None,564+ url.scheme,565+ "all",566+ )567+ for proxy_key in proxy_keys:568+ if proxy_key and proxy_key in self.proxies:569+ dispatcher = self.proxies[proxy_key]570+ return dispatcher571+572+ return self.dispatch573+574+ async def request(575+ self,576+ method: str,577+ url: URLTypes,578+ *,579+ data: RequestData = None,580+ files: RequestFiles = None,581+ json: typing.Any = None,582+ params: QueryParamTypes = None,583+ headers: HeaderTypes = None,584+ cookies: CookieTypes = None,585+ stream: bool = False,586+ auth: AuthTypes = None,587+ allow_redirects: bool = True,588+ cert: CertTypes = None,589+ verify: VerifyTypes = None,590+ timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,591+ trust_env: bool = None,592+ ) -> Response:593+ if cert is not None: # pragma: nocover594+ raise RuntimeError(595+ "Passing a 'cert' argument when making a request on a client "596+ "is not supported anymore. Instantiate a new client instead, "597+ "passing any 'cert' arguments to the client itself."598+ )599+600+ if verify is not None: # pragma: nocover601+ raise RuntimeError(602+ "Passing a 'verify' argument when making a request on a client "603+ "is not supported anymore. Instantiate a new client instead, "604+ "passing any 'verify' arguments to the client itself."605+ )606+607+ if trust_env is not None: # pragma: nocover608+ raise RuntimeError(609+ "Passing a 'trust_env' argument when making a request on a client "610+ "is not supported anymore. Instantiate a new client instead, "611+ "passing any 'trust_env' argument to the client itself."612+ )613+614+ if stream: # pragma: nocover615+ warnings.warn(616+ "The 'stream=True' argument is due to be deprecated. "617+ "Use 'async with client.stream(method, url, ...) as response' instead."618+ )619+620+ request = self.build_request(621+ method=method,622+ url=url,623+ data=data,624+ files=files,625+ json=json,626+ params=params,627+ headers=headers,628+ cookies=cookies,629+ )630+ response = await self.send(631+ request,632+ stream=stream,633+ auth=auth,634+ allow_redirects=allow_redirects,635+ timeout=timeout,636+ )637+ return response638+639+ async def send(640+ self,641+ request: Request,642+ *,643+ stream: bool = False,644+ auth: AuthTypes = None,645+ allow_redirects: bool = True,646+ timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,647+ ) -> Response:648+ if request.url.scheme not in ("http", "https"):649+ raise InvalidURL('URL scheme must be "http" or "https".')650+651+ timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)652+653+ auth = self.build_auth(request, auth)654+655+ response = await self.send_handling_redirects(656+ request, auth=auth, timeout=timeout, allow_redirects=allow_redirects,657+ )658+659+ if not stream:660+ try:661+ await response.aread()662+ finally:663+ await response.aclose()664+665+ return response666+667+ async def send_handling_redirects(668+ self,669+ request: Request,670+ auth: Auth,671+ timeout: Timeout,672+ allow_redirects: bool = True,673+ history: typing.List[Response] = None,674+ ) -> Response:675+ if history is None:676+ history = []677+678+ while True:679+ if len(history) > self.max_redirects:680+ raise TooManyRedirects()681+ if request.url in (response.url for response in history):682+ raise RedirectLoop()683+684+ response = await self.send_handling_auth(685+ request, auth=auth, timeout=timeout, history=history686+ )687+ response.history = list(history)688+689+ if not response.is_redirect:690+ return response691+692+ await response.aread()693+ request = self.build_redirect_request(request, response)694+ history = history + [response]695+696+ if not allow_redirects:697+ response.call_next = functools.partial(698+ self.send_handling_redirects,699+ request=request,700+ auth=auth,701+ timeout=timeout,702+ allow_redirects=False,703+ history=history,704+ )705+ return response706+707 async def send_handling_auth(708 self,709 request: Request,710 history: typing.List[Response],43 unmodified lines754 logger.debug(f'HTTP Request: {request.method} {request.url} "{response_line}"')755 756 return response757 624- def dispatcher_for_url(self, url: URL) -> AsyncDispatcher:625- """626- Returns the AsyncDispatcher instance that should be used for a given URL.627- This will either be the standard connection pool, or a proxy.628- """629- if self.proxies:630- is_default_port = (url.scheme == "http" and url.port == 80) or (631- url.scheme == "https" and url.port == 443632- )633- hostname = f"{url.host}:{url.port}"634- proxy_keys = (635- f"{url.scheme}://{hostname}",636- f"{url.scheme}://{url.host}" if is_default_port else None,637- f"all://{hostname}",638- f"all://{url.host}" if is_default_port else None,639- url.scheme,640- "all",641- )642- for proxy_key in proxy_keys:643- if proxy_key and proxy_key in self.proxies:644- return self.proxies[proxy_key]645-646- return self.dispatch647-758 async def get(759 self,760 url: URLTypes,761 *,235 unmodified lines997 ) -> None:998 await self.aclose()999 1000 891-def _proxies_to_dispatchers(892- proxies: typing.Optional[ProxiesTypes],893- verify: VerifyTypes,894- cert: typing.Optional[CertTypes],895- http2: bool,896- pool_limits: PoolLimits,897- backend: typing.Union[str, ConcurrencyBackend],898- trust_env: bool,899-) -> typing.Dict[str, AsyncDispatcher]:900- def _proxy_from_url(url: URLTypes) -> AsyncDispatcher:901- nonlocal verify, cert, http2, pool_limits, backend, trust_env902- url = URL(url)903- if url.scheme in ("http", "https"):904- return HTTPProxy(905- url,906- verify=verify,907- cert=cert,908- pool_limits=pool_limits,909- backend=backend,910- trust_env=trust_env,911- http2=http2,912- )913- raise ValueError(f"Unknown proxy for {url!r}")914-915- if proxies is None:916- return {}917- elif isinstance(proxies, (str, URL)):918- return {"all": _proxy_from_url(proxies)}919- elif isinstance(proxies, AsyncDispatcher):920- return {"all": proxies}921- else:922- new_proxies = {}923- for key, dispatcher_or_url in proxies.items():924- if isinstance(dispatcher_or_url, (str, URL)):925- new_proxies[str(key)] = _proxy_from_url(dispatcher_or_url)926- else:927- new_proxies[str(key)] = dispatcher_or_url928- return new_proxies929-930-1001 class StreamContextManager:1002 def __init__(1003 self,1004 client: AsyncClient,37 unmodified linesmodified:httpx/config.py+28 added-3 removed
3 unmodified lines4 from pathlib import Path5 6 import certifi7 8-from .__version__ import __version__8+from .models import URL, Headers, HeaderTypes, URLTypes9 from .utils import get_ca_bundle_from_env, get_logger10 11 CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]12 VerifyTypes = typing.Union[str, bool, ssl.SSLContext]13 TimeoutTypes = typing.Union[14 None, float, typing.Tuple[float, float, float, float], "Timeout"15 ]16+ProxiesTypes = typing.Union[17+ URLTypes, "Proxy", typing.Dict[URLTypes, typing.Union[URLTypes, "Proxy"]]18+]19 20 18-USER_AGENT = f"python-httpx/{__version__}"19-21 DEFAULT_CIPHERS = ":".join(22 [23 "ECDHE+AESGCM",24 "ECDHE+CHACHA20",280 unmodified lines305 f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit})"306 )307 308 309+class Proxy:310+ def __init__(311+ self, url: URLTypes, *, headers: HeaderTypes = None, mode: str = "DEFAULT",312+ ):313+ url = URL(url)314+ headers = Headers(headers)315+316+ if url.scheme not in ("http", "https"):317+ raise ValueError(f"Unknown scheme for proxy URL {url!r}")318+ if mode not in ("DEFAULT", "CONNECT_ONLY", "TUNNEL_ONLY"):319+ raise ValueError(f"Unknown proxy mode {mode!r}")320+321+ self.url = url322+ self.headers = headers323+ self.mode = mode324+325+ def __repr__(self) -> str:326+ return (327+ f"Proxy(url={str(self.url)!r}, "328+ f"headers={dict(self.headers)!r}, "329+ f"mode={self.mode!r})"330+ )331+332+333 TimeoutConfig = Timeout # Synonym for backwards compat334 335 336 DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0)2 unmodified linesmodified:httpx/decoders.py-5 removed
280 unmodified lines281 282 283 if brotli is None:284 SUPPORTED_DECODERS.pop("br") # pragma: nocover285-286-287-ACCEPT_ENCODING = ", ".join(288- [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]289-)modified:httpx/models.py+7 added-8 removed
10 unmodified lines11 12 import chardet13 import rfc398614 15-from .config import USER_AGENT15+from .__version__ import __version__16 from .content_streams import (17 ByteStream,18 ContentStream,19 RequestData,20 RequestFiles,21 encode,22 )23 from .decoders import (24- ACCEPT_ENCODING,24 SUPPORTED_DECODERS,25 Decoder,26 IdentityDecoder,27 LineDecoder,43 unmodified lines71 ]72 73 CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]74 76-ProxiesTypes = typing.Union[77- URLTypes,78- "AsyncDispatcher",79- typing.Dict[URLTypes, typing.Union[URLTypes, "AsyncDispatcher"]],80-]75 82-76 class URL:77 def __init__(78 self,79 url: URLTypes,501 unmodified lines581 return f"{class_name}({as_dict!r}{encoding_str})"582 return f"{class_name}({as_list!r}{encoding_str})"583 584 585+USER_AGENT = f"python-httpx/{__version__}"586+ACCEPT_ENCODING = ", ".join(587+ [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]588+)589+590+591 class Request:592 def __init__(593 self,594 method: str,583 unmodified linesmodified:tests/client/test_proxies.py+2 added-2 removed
10 unmodified lines11 (12 {"http": "http://127.0.0.1", "https": "https://127.0.0.1"},13 [("http", "http://127.0.0.1"), ("https", "https://127.0.0.1")],14 ),15- (httpx.HTTPProxy("http://127.0.0.1"), [("all", "http://127.0.0.1")]),15+ (httpx.Proxy("http://127.0.0.1"), [("all", "http://127.0.0.1")]),16 (17- {"https": httpx.HTTPProxy("https://127.0.0.1"), "all": "http://127.0.0.1"},17+ {"https": httpx.Proxy("https://127.0.0.1"), "all": "http://127.0.0.1"},18 [("all", "http://127.0.0.1"), ("https", "https://127.0.0.1")],19 ),20 ],21 )69 unmodified linesmodified:tests/test_config.py+15 added
204 unmodified lines205 206 ssl_config = SSLConfig(trust_env=False)207 208 assert ssl_config.ssl_context.keylog_filename is None209+210+211+def test_proxy_from_url():212+ proxy = httpx.Proxy("https://example.com")213+ assert repr(proxy) == "Proxy(url='https://example.com', headers={}, mode='DEFAULT')"214+215+216+def test_invalid_proxy_scheme():217+ with pytest.raises(ValueError):218+ httpx.Proxy("invalid://example.com")219+220+221+def test_invalid_proxy_mode():222+ with pytest.raises(ValueError):223+ httpx.Proxy("https://example.com", mode="INVALID")