Skip to content
Myr

Context managed transports (#1218)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Context managed transports * Update httpx/_client.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Update httpx/_client.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Update tests/client/test_client.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Update tests/client/test_async_client.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Code comment around close/__enter__/__exit__ interaction

authored by Tom Christie · committed by GitHub · parent 4161d7a · Browse files · 3 files+95 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Florimond Manca <florimond.manca@gmail.com>

Diff stats

3 files+95 added−2 removed

  • tests:+79 added−0 removed
  • other:+16 added−2 removed

3 files+95 added−2 removed

modified:httpx/_client.py+16 added-2 removed
1033 unmodified lines
1034 if proxy is not None:1035 proxy.close()10361037 def __enter__(self) -> "Client":1038 self._transport.__enter__()1039 for proxy in self._proxies.values():1040 if proxy is not None:1041 proxy.__enter__()1042 return self10431044 def __exit__(1045 self,1046 exc_type: typing.Type[BaseException] = None,1047 exc_value: BaseException = None,1048 traceback: TracebackType = None,1049 ) -> None:1046 self.close()1050 self._transport.__exit__(exc_type, exc_value, traceback)1051 for proxy in self._proxies.values():1052 if proxy is not None:1053 proxy.__exit__(exc_type, exc_value, traceback)105410551056class AsyncClient(BaseClient):1057 """
587 unmodified lines
1645 if proxy is not None:1646 await proxy.aclose()16471648 async def __aenter__(self) -> "AsyncClient":1649 await self._transport.__aenter__()1650 for proxy in self._proxies.values():1651 if proxy is not None:1652 await proxy.__aenter__()1653 return self16541655 async def __aexit__(1656 self,1657 exc_type: typing.Type[BaseException] = None,1658 exc_value: BaseException = None,1659 traceback: TracebackType = None,1660 ) -> None:1650 await self.aclose()1661 await self._transport.__aexit__(exc_type, exc_value, traceback)1662 for proxy in self._proxies.values():1663 if proxy is not None:1664 await proxy.__aexit__(exc_type, exc_value, traceback)166516661667class StreamContextManager:1668 def __init__(
57 unmodified lines
modified:tests/client/test_async_client.py+40 added
1from datetime import timedelta23import httpcore4import pytest56import httpx7
158 unmodified lines
166 )167168 assert response.status_code == 200169 assert response.content == data170171172@pytest.mark.usefixtures("async_environment")173async def test_context_managed_transport():174 class Transport(httpcore.AsyncHTTPTransport):175 def __init__(self):176 self.events = []177178 async def aclose(self):179 # The base implementation of httpcore.AsyncHTTPTransport just180 # calls into `.aclose`, so simple transport cases can just override181 # this method for any cleanup, where more complex cases182 # might want to additionally override `__aenter__`/`__aexit__`.183 self.events.append("transport.aclose")184185 async def __aenter__(self):186 await super().__aenter__()187 self.events.append("transport.__aenter__")188189 async def __aexit__(self, *args):190 await super().__aexit__(*args)191 self.events.append("transport.__aexit__")192193 # Note that we're including 'proxies' here to *also* run through the194 # proxy context management, although we can't easily test that at the195 # moment, since we can't add proxies as transport instances.196 #197 # Once we have a more generalised Mount API we'll be able to remove this198 # in favour of ensuring all mounts are context managed, which will199 # also neccessarily include proxies.200 transport = Transport()201 async with httpx.AsyncClient(transport=transport, proxies="http://www.example.com"):202 pass203204 assert transport.events == [205 "transport.__aenter__",206 "transport.aclose",207 "transport.__aexit__",208 ]
modified:tests/client/test_client.py+39 added
1from datetime import timedelta23import httpcore4import pytest56import httpx7
200 unmodified lines
208 httpx.Client(pool_limits=limits)209210 with pytest.warns(DeprecationWarning):211 httpx.AsyncClient(pool_limits=limits)212213214def test_context_managed_transport():215 class Transport(httpcore.SyncHTTPTransport):216 def __init__(self):217 self.events = []218219 def close(self):220 # The base implementation of httpcore.SyncHTTPTransport just221 # calls into `.close`, so simple transport cases can just override222 # this method for any cleanup, where more complex cases223 # might want to additionally override `__enter__`/`__exit__`.224 self.events.append("transport.close")225226 def __enter__(self):227 super().__enter__()228 self.events.append("transport.__enter__")229230 def __exit__(self, *args):231 super().__exit__(*args)232 self.events.append("transport.__exit__")233234 # Note that we're including 'proxies' here to *also* run through the235 # proxy context management, although we can't easily test that at the236 # moment, since we can't add proxies as transport instances.237 #238 # Once we have a more generalised Mount API we'll be able to remove this239 # in favour of ensuring all mounts are context managed, which will240 # also neccessarily include proxies.241 transport = Transport()242 with httpx.Client(transport=transport, proxies="http://www.example.com"):243 pass244245 assert transport.events == [246 "transport.__enter__",247 "transport.close",248 "transport.__exit__",249 ]