Skip to content
Myr

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

5 files+233 added−43 removed

modified:docs/advanced.md+54 added-2 removed
1038 unmodified lines
1039 """1040 A mock transport that always returns a JSON "Hello, world!" response.1041 """10421043 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```10511052Which we can use in the same way:1053
3 unmodified lines
1057>>> response = client.get("https://example.org/")1058>>> response.json()1059{"text": "Hello, world!"}1060```10611062### Mounting transports10631064You can also mount transports against given schemes or domains, to control1065which transport an outgoing request should be routed via, with [the same style1066used for specifying proxy routing](#routing).10671068```python1069import httpcore1070import httpx10711072class HTTPSRedirectTransport(httpcore.SyncHTTPTransport):1073 """1074 A transport that always redirects to HTTPS.1075 """10761077 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, ext108710881089# A client where any `http` requests are always redirected to `https`1090mounts = {'http://': HTTPSRedirectTransport()}1091client = httpx.Client(mounts=mounts)1092```10931094A couple of other sketches of how you might take advantage of mounted transports...10951096Mocking requests to a given domain:10971098```python1099# All requests to "example.org" should be mocked out.1100# Other requests occur as usual.1101mounts = {"all://example.org": MockTransport()}1102client = httpx.Client(mounts=mounts)1103```11041105Adding support for custom schemes:11061107```python1108# Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html"1109mounts = {"file://": FileSystemTransport()}1110client = httpx.Client(mounts=mounts)1111```
modified:httpx/_client.py+33 added-22 removed
85 unmodified lines
86 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_hooks
465 unmodified lines
560 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 lines
611 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 None
6 unmodified lines
626 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 )634635 self._mounts = dict(sorted(self._mounts.items()))636637 def _init_transport(638 self,639 verify: VerifyTypes = True,640 cert: CertTypes = None,
45 unmodified lines
686 """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 transport693694 return self._transport
419 unmodified lines
1114 if self._state != ClientState.CLOSED:1115 self._state = ClientState.CLOSED11161117 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()11211122 def __enter__(self: T) -> T:1123 self._state = ClientState.OPENED11241125 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 self11301131 def __exit__(1132 self,
3 unmodified lines
1136 ) -> None:1137 self._state = ClientState.CLOSED11381139 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)11431144 def __del__(self) -> None:1145 self.close()1146
56 unmodified lines
1203 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 lines
1255 app=app,1256 trust_env=trust_env,1257 )12581252 self._proxies: typing.Dict[1259 self._mounts: typing.Dict[1260 URLPattern, typing.Optional[httpcore.AsyncHTTPTransport]1261 ] = {1262 URLPattern(key): None1263 if proxy is None
6 unmodified lines
1270 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()))12791280 def _init_transport(1281 self,1282 verify: VerifyTypes = True,
46 unmodified lines
1329 """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 transport13361337 return self._transport
171 unmodified lines
1509 timer = Timer()1510 await timer.async_start()15111512 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: ignore
242 unmodified lines
1760 if self._state != ClientState.CLOSED:1761 self._state = ClientState.CLOSED17621763 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()17671768 async def __aenter__(self: U) -> U:1769 self._state = ClientState.OPENED17701771 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 lines
1782 ) -> None:1783 self._state = ClientState.CLOSED17841785 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)17891790 def __del__(self) -> None:
67 unmodified lines
modified:tests/client/test_async_client.py+68 added-8 removed
1import typing2from datetime import timedelta34import httpcore5import pytest
182 unmodified lines
188 async def __aexit__(self, *args):189 await super().__aexit__(*args)190 self.events.append("transport.__aexit__")191191 # 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 pass195196 assert transport.events == [197 "transport.__aenter__",
1 unmodified line
199 "transport.__aexit__",200 ]201202203@pytest.mark.usefixtures("async_environment")204async 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] = []209210 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")216217 async def __aenter__(self):218 await super().__aenter__()219 self.events.append(f"{self.name}.__aenter__")220221 async def __aexit__(self, *args):222 await super().__aexit__(*args)223 self.events.append(f"{self.name}.__aexit__")224225 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 pass231232 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 ]242243244def hello_world(request):245 return httpx.Response(200, text="Hello, world!")246247
28 unmodified lines
276 client = httpx.AsyncClient(transport=MockTransport(hello_world))277 await client.get("http://example.com")278 with pytest.warns(UserWarning):279 del client280281282def unmounted(request: httpx.Request) -> httpx.Response:283 data = {"app": "unmounted"}284 return httpx.Response(200, json=data)285286287def mounted(request: httpx.Request) -> httpx.Response:288 data = {"app": "mounted"}289 return httpx.Response(200, json=data)290291292@pytest.mark.usefixtures("async_environment")293async def test_mounted_transport():294 transport = MockTransport(unmounted)295 mounts = {"custom://": MockTransport(mounted)}296297 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"}301302 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
1import typing2from datetime import timedelta34import httpcore5import pytest
221 unmodified lines
227 def __exit__(self, *args):228 super().__exit__(*args)229 self.events.append("transport.__exit__")230230 # 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 pass234235 assert transport.events == [236 "transport.__enter__",
1 unmodified line
238 "transport.__exit__",239 ]240241242def 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] = []247248 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")254255 def __enter__(self):256 super().__enter__()257 self.events.append(f"{self.name}.__enter__")258259 def __exit__(self, *args):260 super().__exit__(*args)261 self.events.append(f"{self.name}.__exit__")262263 transport = Transport(name="transport")264 mounted = Transport(name="mounted")265 with httpx.Client(transport=transport, mounts={"http://www.example.org": mounted}):266 pass267268 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 ]278279280def hello_world(request):281 return httpx.Response(200, text="Hello, world!")282283
47 unmodified lines
331 ["Connection", "keep-alive"],332 ["User-Agent", f"python-httpx/{httpx.__version__}"],333 ["Example-Header", "example-value"],334 ]335336337def unmounted(request: httpx.Request) -> httpx.Response:338 data = {"app": "unmounted"}339 return httpx.Response(200, json=data)340341342def mounted(request: httpx.Request) -> httpx.Response:343 data = {"app": "mounted"}344 return httpx.Response(200, json=data)345346347def test_mounted_transport():348 transport = MockTransport(unmounted)349 mounts = {"custom://": MockTransport(mounted)}350351 client = httpx.Client(transport=transport, mounts=mounts)352353 response = client.get("https://www.example.com")354 assert response.status_code == 200355 assert response.json() == {"app": "unmounted"}356357 response = client.get("custom://www.example.com")358 assert response.status_code == 200359 assert response.json() == {"app": "mounted"}360361362def test_all_mounted_transport():363 mounts = {"all://": MockTransport(mounted)}364365 client = httpx.Client(mounts=mounts)366367 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 lines
40 client = httpx.Client(proxies=proxies)4142 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)4849 assert len(expected_proxies) == len(client._proxies)49 assert len(expected_proxies) == len(client._mounts)505152PROXY_URL = "http://[::1]"53
217 unmodified lines