Add support for Mount API (#1362)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add support for Mount API * Add test cases * Add test case for all: mounted transport * Use 'transport' variable, in preference to 'proxy' * Add docs for mounted transports
authored by Tom Christie · committed by GitHub · parent 2961f26 · Browse files · 5 files·+233 added−43 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+233 added−43 removed
- tests:+146 added−19 removed
- other:+87 added−24 removed
Provenance
- Commit
c4d2e6f- Tree
4a219f4- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
2961f26
5 files changed+233 added−43 removed
modified:docs/advanced.md+54 added-2 removed
1038 unmodified lines1039 """1040 A mock transport that always returns a JSON "Hello, world!" response.1041 """1042 1043- def request(self, method, url, headers=None, stream=None, timeout=None):1043+ def request(self, method, url, headers=None, stream=None, ext=None):1044 message = {"text": "Hello, world!"}1045 content = json.dumps(message).encode("utf-8")1046 stream = httpcore.PlainByteStream(content)1047 headers = [(b"content-type", b"application/json")]1048- return b"HTTP/1.1", 200, b"OK", headers, stream1048+ ext = {"http_version": b"HTTP/1.1"}1049+ return 200, headers, stream, ext1050 ```1051 1052 Which we can use in the same way:1053 3 unmodified lines1057 >>> response = client.get("https://example.org/")1058 >>> response.json()1059 {"text": "Hello, world!"}1060 ```1061+1062+### Mounting transports1063+1064+You can also mount transports against given schemes or domains, to control1065+which transport an outgoing request should be routed via, with [the same style1066+used for specifying proxy routing](#routing).1067+1068+```python1069+import httpcore1070+import httpx1071+1072+class HTTPSRedirectTransport(httpcore.SyncHTTPTransport):1073+ """1074+ A transport that always redirects to HTTPS.1075+ """1076+1077+ def request(self, method, url, headers=None, stream=None, ext=None):1078+ scheme, host, port, path = url1079+ if port is None:1080+ location = b"https://%s%s" % (host, path)1081+ else:1082+ location = b"https://%s:%d%s" % (host, port, path)1083+ stream = httpcore.PlainByteStream(b"")1084+ headers = [(b"location", location)]1085+ ext = {"http_version": b"HTTP/1.1"}1086+ return 303, headers, stream, ext1087+1088+1089+# A client where any `http` requests are always redirected to `https`1090+mounts = {'http://': HTTPSRedirectTransport()}1091+client = httpx.Client(mounts=mounts)1092+```1093+1094+A couple of other sketches of how you might take advantage of mounted transports...1095+1096+Mocking requests to a given domain:1097+1098+```python1099+# All requests to "example.org" should be mocked out.1100+# Other requests occur as usual.1101+mounts = {"all://example.org": MockTransport()}1102+client = httpx.Client(mounts=mounts)1103+```1104+1105+Adding support for custom schemes:1106+1107+```python1108+# Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html"1109+mounts = {"file://": FileSystemTransport()}1110+client = httpx.Client(mounts=mounts)1111+```modified:httpx/_client.py+33 added-22 removed
85 unmodified lines86 headers: HeaderTypes = None,87 cookies: CookieTypes = None,88 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,89 max_redirects: int = DEFAULT_MAX_REDIRECTS,90- event_hooks: typing.Dict[str, typing.List[typing.Callable]] = None,90+ event_hooks: typing.Mapping[str, typing.List[typing.Callable]] = None,91 base_url: URLTypes = "",92 trust_env: bool = True,93 ):94 event_hooks = {} if event_hooks is None else event_hooks465 unmodified lines560 verify: VerifyTypes = True,561 cert: CertTypes = None,562 http2: bool = False,563 proxies: ProxiesTypes = None,564+ mounts: typing.Mapping[str, httpcore.SyncHTTPTransport] = None,565 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,566 limits: Limits = DEFAULT_LIMITS,567 pool_limits: Limits = None,568 max_redirects: int = DEFAULT_MAX_REDIRECTS,568- event_hooks: typing.Dict[str, typing.List[typing.Callable]] = None,569+ event_hooks: typing.Mapping[str, typing.List[typing.Callable]] = None,570 base_url: URLTypes = "",571 transport: httpcore.SyncHTTPTransport = None,572 app: typing.Callable = None,573 trust_env: bool = True,37 unmodified lines611 transport=transport,612 app=app,613 trust_env=trust_env,614 )614- self._proxies: typing.Dict[615+ self._mounts: typing.Dict[616 URLPattern, typing.Optional[httpcore.SyncHTTPTransport]617 ] = {618 URLPattern(key): None619 if proxy is None6 unmodified lines626 trust_env=trust_env,627 )628 for key, proxy in proxy_map.items()629 }629- self._proxies = dict(sorted(self._proxies.items()))630+ if mounts is not None:631+ self._mounts.update(632+ {URLPattern(key): transport for key, transport in mounts.items()}633+ )634 635+ self._mounts = dict(sorted(self._mounts.items()))636+637 def _init_transport(638 self,639 verify: VerifyTypes = True,640 cert: CertTypes = None,45 unmodified lines686 """687 Returns the transport instance that should be used for a given URL.688 This will either be the standard connection pool, or a proxy.689 """684- for pattern, transport in self._proxies.items():690+ for pattern, transport in self._mounts.items():691 if pattern.matches(url):692 return self._transport if transport is None else transport693 694 return self._transport419 unmodified lines1114 if self._state != ClientState.CLOSED:1115 self._state = ClientState.CLOSED1116 1117 self._transport.close()1112- for proxy in self._proxies.values():1113- if proxy is not None:1114- proxy.close()1118+ for transport in self._mounts.values():1119+ if transport is not None:1120+ transport.close()1121 1122 def __enter__(self: T) -> T:1123 self._state = ClientState.OPENED1124 1125 self._transport.__enter__()1120- for proxy in self._proxies.values():1121- if proxy is not None:1122- proxy.__enter__()1126+ for transport in self._mounts.values():1127+ if transport is not None:1128+ transport.__enter__()1129 return self1130 1131 def __exit__(1132 self,3 unmodified lines1136 ) -> None:1137 self._state = ClientState.CLOSED1138 1139 self._transport.__exit__(exc_type, exc_value, traceback)1134- for proxy in self._proxies.values():1135- if proxy is not None:1136- proxy.__exit__(exc_type, exc_value, traceback)1140+ for transport in self._mounts.values():1141+ if transport is not None:1142+ transport.__exit__(exc_type, exc_value, traceback)1143 1144 def __del__(self) -> None:1145 self.close()1146 56 unmodified lines1203 verify: VerifyTypes = True,1204 cert: CertTypes = None,1205 http2: bool = False,1206 proxies: ProxiesTypes = None,1207+ mounts: typing.Mapping[str, httpcore.AsyncHTTPTransport] = None,1208 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,1209 limits: Limits = DEFAULT_LIMITS,1210 pool_limits: Limits = None,1211 max_redirects: int = DEFAULT_MAX_REDIRECTS,1205- event_hooks: typing.Dict[str, typing.List[typing.Callable]] = None,1212+ event_hooks: typing.Mapping[str, typing.List[typing.Callable]] = None,1213 base_url: URLTypes = "",1214 transport: httpcore.AsyncHTTPTransport = None,1215 app: typing.Callable = None,1216 trust_env: bool = True,38 unmodified lines1255 app=app,1256 trust_env=trust_env,1257 )1258 1252- self._proxies: typing.Dict[1259+ self._mounts: typing.Dict[1260 URLPattern, typing.Optional[httpcore.AsyncHTTPTransport]1261 ] = {1262 URLPattern(key): None1263 if proxy is None6 unmodified lines1270 trust_env=trust_env,1271 )1272 for key, proxy in proxy_map.items()1273 }1267- self._proxies = dict(sorted(self._proxies.items()))1274+ if mounts is not None:1275+ self._mounts.update(1276+ {URLPattern(key): transport for key, transport in mounts.items()}1277+ )1278+ self._mounts = dict(sorted(self._mounts.items()))1279 1280 def _init_transport(1281 self,1282 verify: VerifyTypes = True,46 unmodified lines1329 """1330 Returns the transport instance that should be used for a given URL.1331 This will either be the standard connection pool, or a proxy.1332 """1322- for pattern, transport in self._proxies.items():1333+ for pattern, transport in self._mounts.items():1334 if pattern.matches(url):1335 return self._transport if transport is None else transport1336 1337 return self._transport171 unmodified lines1509 timer = Timer()1510 await timer.async_start()1511 1512 with map_exceptions(HTTPCORE_EXC_MAP, request=request):1502- (status_code, headers, stream, ext,) = await transport.arequest(1513+ (status_code, headers, stream, ext) = await transport.arequest(1514 request.method.encode(),1515 request.url.raw,1516 headers=request.headers.raw,1517 stream=request.stream, # type: ignore242 unmodified lines1760 if self._state != ClientState.CLOSED:1761 self._state = ClientState.CLOSED1762 1763 await self._transport.aclose()1753- for proxy in self._proxies.values():1764+ for proxy in self._mounts.values():1765 if proxy is not None:1766 await proxy.aclose()1767 1768 async def __aenter__(self: U) -> U:1769 self._state = ClientState.OPENED1770 1771 await self._transport.__aenter__()1761- for proxy in self._proxies.values():1772+ for proxy in self._mounts.values():1773 if proxy is not None:1774 await proxy.__aenter__()1775 return self1776 5 unmodified lines1782 ) -> None:1783 self._state = ClientState.CLOSED1784 1785 await self._transport.__aexit__(exc_type, exc_value, traceback)1775- for proxy in self._proxies.values():1786+ for proxy in self._mounts.values():1787 if proxy is not None:1788 await proxy.__aexit__(exc_type, exc_value, traceback)1789 1790 def __del__(self) -> None:67 unmodified linesmodified:tests/client/test_async_client.py+68 added-8 removed
1+import typing2 from datetime import timedelta3 4 import httpcore5 import pytest182 unmodified lines188 async def __aexit__(self, *args):189 await super().__aexit__(*args)190 self.events.append("transport.__aexit__")191 191- # Note that we're including 'proxies' here to *also* run through the192- # proxy context management, although we can't easily test that at the193- # moment, since we can't add proxies as transport instances.194- #195- # Once we have a more generalised Mount API we'll be able to remove this196- # in favour of ensuring all mounts are context managed, which will197- # also neccessarily include proxies.192 transport = Transport()199- async with httpx.AsyncClient(transport=transport, proxies="http://www.example.com"):193+ async with httpx.AsyncClient(transport=transport):194 pass195 196 assert transport.events == [197 "transport.__aenter__",1 unmodified line199 "transport.__aexit__",200 ]201 202 203+@pytest.mark.usefixtures("async_environment")204+async def test_context_managed_transport_and_mount():205+ class Transport(httpcore.AsyncHTTPTransport):206+ def __init__(self, name: str):207+ self.name: str = name208+ self.events: typing.List[str] = []209+210+ async def aclose(self):211+ # The base implementation of httpcore.AsyncHTTPTransport just212+ # calls into `.aclose`, so simple transport cases can just override213+ # this method for any cleanup, where more complex cases214+ # might want to additionally override `__aenter__`/`__aexit__`.215+ self.events.append(f"{self.name}.aclose")216+217+ async def __aenter__(self):218+ await super().__aenter__()219+ self.events.append(f"{self.name}.__aenter__")220+221+ async def __aexit__(self, *args):222+ await super().__aexit__(*args)223+ self.events.append(f"{self.name}.__aexit__")224+225+ transport = Transport(name="transport")226+ mounted = Transport(name="mounted")227+ async with httpx.AsyncClient(228+ transport=transport, mounts={"http://www.example.org": mounted}229+ ):230+ pass231+232+ assert transport.events == [233+ "transport.__aenter__",234+ "transport.aclose",235+ "transport.__aexit__",236+ ]237+ assert mounted.events == [238+ "mounted.__aenter__",239+ "mounted.aclose",240+ "mounted.__aexit__",241+ ]242+243+244 def hello_world(request):245 return httpx.Response(200, text="Hello, world!")246 247 28 unmodified lines276 client = httpx.AsyncClient(transport=MockTransport(hello_world))277 await client.get("http://example.com")278 with pytest.warns(UserWarning):279 del client280+281+282+def unmounted(request: httpx.Request) -> httpx.Response:283+ data = {"app": "unmounted"}284+ return httpx.Response(200, json=data)285+286+287+def mounted(request: httpx.Request) -> httpx.Response:288+ data = {"app": "mounted"}289+ return httpx.Response(200, json=data)290+291+292+@pytest.mark.usefixtures("async_environment")293+async def test_mounted_transport():294+ transport = MockTransport(unmounted)295+ mounts = {"custom://": MockTransport(mounted)}296+297+ async with httpx.AsyncClient(transport=transport, mounts=mounts) as client:298+ response = await client.get("https://www.example.com")299+ assert response.status_code == 200300+ assert response.json() == {"app": "unmounted"}301+302+ response = await client.get("custom://www.example.com")303+ assert response.status_code == 200304+ assert response.json() == {"app": "mounted"}modified:tests/client/test_client.py+75 added-8 removed
1+import typing2 from datetime import timedelta3 4 import httpcore5 import pytest221 unmodified lines227 def __exit__(self, *args):228 super().__exit__(*args)229 self.events.append("transport.__exit__")230 230- # Note that we're including 'proxies' here to *also* run through the231- # proxy context management, although we can't easily test that at the232- # moment, since we can't add proxies as transport instances.233- #234- # Once we have a more generalised Mount API we'll be able to remove this235- # in favour of ensuring all mounts are context managed, which will236- # also neccessarily include proxies.231 transport = Transport()238- with httpx.Client(transport=transport, proxies="http://www.example.com"):232+ with httpx.Client(transport=transport):233 pass234 235 assert transport.events == [236 "transport.__enter__",1 unmodified line238 "transport.__exit__",239 ]240 241 242+def test_context_managed_transport_and_mount():243+ class Transport(httpcore.SyncHTTPTransport):244+ def __init__(self, name: str):245+ self.name: str = name246+ self.events: typing.List[str] = []247+248+ def close(self):249+ # The base implementation of httpcore.SyncHTTPTransport just250+ # calls into `.close`, so simple transport cases can just override251+ # this method for any cleanup, where more complex cases252+ # might want to additionally override `__enter__`/`__exit__`.253+ self.events.append(f"{self.name}.close")254+255+ def __enter__(self):256+ super().__enter__()257+ self.events.append(f"{self.name}.__enter__")258+259+ def __exit__(self, *args):260+ super().__exit__(*args)261+ self.events.append(f"{self.name}.__exit__")262+263+ transport = Transport(name="transport")264+ mounted = Transport(name="mounted")265+ with httpx.Client(transport=transport, mounts={"http://www.example.org": mounted}):266+ pass267+268+ assert transport.events == [269+ "transport.__enter__",270+ "transport.close",271+ "transport.__exit__",272+ ]273+ assert mounted.events == [274+ "mounted.__enter__",275+ "mounted.close",276+ "mounted.__exit__",277+ ]278+279+280 def hello_world(request):281 return httpx.Response(200, text="Hello, world!")282 283 47 unmodified lines331 ["Connection", "keep-alive"],332 ["User-Agent", f"python-httpx/{httpx.__version__}"],333 ["Example-Header", "example-value"],334 ]335+336+337+def unmounted(request: httpx.Request) -> httpx.Response:338+ data = {"app": "unmounted"}339+ return httpx.Response(200, json=data)340+341+342+def mounted(request: httpx.Request) -> httpx.Response:343+ data = {"app": "mounted"}344+ return httpx.Response(200, json=data)345+346+347+def test_mounted_transport():348+ transport = MockTransport(unmounted)349+ mounts = {"custom://": MockTransport(mounted)}350+351+ client = httpx.Client(transport=transport, mounts=mounts)352+353+ response = client.get("https://www.example.com")354+ assert response.status_code == 200355+ assert response.json() == {"app": "unmounted"}356+357+ response = client.get("custom://www.example.com")358+ assert response.status_code == 200359+ assert response.json() == {"app": "mounted"}360+361+362+def test_all_mounted_transport():363+ mounts = {"all://": MockTransport(mounted)}364+365+ client = httpx.Client(mounts=mounts)366+367+ response = client.get("https://www.example.com")368+ assert response.status_code == 200369+ assert response.json() == {"app": "mounted"}modified:tests/client/test_proxies.py+3 added-3 removed
39 unmodified lines40 client = httpx.Client(proxies=proxies)41 42 for proxy_key, url in expected_proxies:43 pattern = URLPattern(proxy_key)44- assert pattern in client._proxies45- proxy = client._proxies[pattern]44+ assert pattern in client._mounts45+ proxy = client._mounts[pattern]46 assert isinstance(proxy, httpcore.SyncHTTPProxy)47 assert proxy.proxy_origin == url_to_origin(url)48 49- assert len(expected_proxies) == len(client._proxies)49+ assert len(expected_proxies) == len(client._mounts)50 51 52 PROXY_URL = "http://[::1]"53 217 unmodified lines