Add `HTTPTransport` and `AsyncHTTPTransport` (#1399)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add keepalive_expiry to Limits config * keepalive_expiry should be optional. In line with httpcore. * HTTPTransport and AsyncHTTPTransport * Update docs for httpx.HTTPTransport() * Update type hints * Fix docs typo * Additional mount example * Tweak context manager methods * Add 'httpx.HTTPTransport(proxy=...)' * Use explicit keyword arguments throughout httpx.HTTPTransport
authored by Tom Christie · committed by GitHub · parent 1816393 · Browse files · 6 files·+242 added−70 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
6 files+242 added−70 removed
- tests:+7 added−5 removed
- other:+235 added−65 removed
Provenance
- Commit
89fb0cb- Tree
a71a12c- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
1816393
6 files changed+242 added−70 removed
modified:docs/advanced.md+28 added-28 removed
969 unmodified lines970 971 ### Usage972 973 For some advanced configuration you might need to instantiate a transport974-class directly, and pass it to the client instance. The `httpcore` package975-provides a `local_address` configuration that is only available via this976-low-level API.974+class directly, and pass it to the client instance. One example is the975+`local_address` configuration which is only available via this low-level API.976 977 ```pycon979->>> import httpx, httpcore980->>> ssl_context = httpx.create_ssl_context()981->>> transport = httpcore.SyncConnectionPool(982-... ssl_context=ssl_context,983-... max_connections=100,984-... max_keepalive_connections=20,985-... keepalive_expiry=5.0,986-... local_address="0.0.0.0"987-... ) # Use the standard HTTPX defaults, but with an IPv4 only 'local_address'.978+>>> import httpx979+>>> transport = httpx.HTTPTransport(local_address="0.0.0.0")980 >>> client = httpx.Client(transport=transport)981 ```982 991-Similarly, `httpcore` provides a `uds` option for connecting via a Unix Domain Socket that is only available via this low-level API:983+Connection retries are also available via this interface.984 993-```python994->>> import httpx, httpcore995->>> ssl_context = httpx.create_ssl_context()996->>> transport = httpcore.SyncConnectionPool(997-... ssl_context=ssl_context,998-... max_connections=100,999-... max_keepalive_connections=20,1000-... keepalive_expiry=5.0,1001-... uds="/var/run/docker.sock",1002-... ) # Connect to the Docker API via a Unix Socket.985+```pycon986+>>> import httpx987+>>> transport = httpx.HTTPTransport(retries=1)988 >>> client = httpx.Client(transport=transport)989+```990+991+Similarly, instantiating a transport directly provides a `uds` option for992+connecting via a Unix Domain Socket that is only available via this low-level API:993+994+```pycon995+>>> import httpx996+>>> # Connect to the Docker API via a Unix Socket.997+>>> transport = httpx.HTTPTransport(uds="/var/run/docker.sock")998+>>> client = httpx.Client(transport=transport)999 >>> response = client.get("http://docker/info")1000 >>> response.json()1001 {"ID": "...", "Containers": 4, "Images": 74, ...}1002 ```1003 1009-Unlike the `httpx.Client()`, the lower-level `httpcore` transport instances1010-do not include any default values for configuring aspects such as the1011-connection pooling details, so you'll need to provide more explicit1012-configuration when using this API.1013-1004 ### urllib3 transport1005 1006 This [public gist](https://gist.github.com/florimondmanca/d56764d78d748eb9f73165da388e546e) provides a transport that uses the excellent [`urllib3` library](https://urllib3.readthedocs.io/en/latest/), and can be used with the sync `Client`...1007 102 unmodified lines1110 ```1111 1112 A couple of other sketches of how you might take advantage of mounted transports...1113 1114+Disabling HTTP/2 on a single given domain...1115+1116+```python1117+mounts = {1118+ "all://": httpx.HTTPTransport(http2=True),1119+ "all://*example.org": httpx.HTTPTransport()1120+}1121+client = httpx.Client(mounts=mounts)1122+```1123+1124 Mocking requests to a given domain:1125 1126 ```python1127 # All requests to "example.org" should be mocked out.15 unmodified linesmodified:docs/async.md+13 added
110 unmodified lines111 112 await client.post(url, data=upload_bytes())113 ```114 115+### Explicit transport instances116+117+When instantiating a transport instance directly, you need to use `httpx.AsyncHTTPTransport`.118+119+For instance:120+121+```pycon122+>>> import httpx123+>>> transport = httpx.AsyncHTTPTransport(retries=1)124+>>> async with httpx.AsyncClient(transport=transport) as client:125+>>> ...126+```127+128 ## Supported async environments129 130 HTTPX supports either `asyncio` or `trio` as an async environment.131 108 unmodified linesadded:httpx/_transports/default.py+174 added
1+"""2+Custom transports, with nicely configured defaults.3+4+The following additional keyword arguments are currently supported by httpcore...5+6+* uds: str7+* local_address: str8+* retries: int9+* backend: str ("auto", "asyncio", "trio", "curio", "anyio", "sync")10+11+Example usages...12+13+# Disable HTTP/2 on a single specfic domain.14+mounts = {15+ "all://": httpx.HTTPTransport(http2=True),16+ "all://*example.org": httpx.HTTPTransport()17+}18+19+# Using advanced httpcore configuration, with connection retries.20+transport = httpx.HTTPTransport(retries=1)21+client = httpx.Client(transport=transport)22+23+# Using advanced httpcore configuration, with unix domain sockets.24+transport = httpx.HTTPTransport(uds="socket.uds")25+client = httpx.Client(transport=transport)26+"""27+import typing28+from types import TracebackType29+30+import httpcore31+32+from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context33+from .._types import CertTypes, VerifyTypes34+35+T = typing.TypeVar("T", bound="HTTPTransport")36+A = typing.TypeVar("A", bound="AsyncHTTPTransport")37+Headers = typing.List[typing.Tuple[bytes, bytes]]38+URL = typing.Tuple[bytes, bytes, typing.Optional[int], bytes]39+40+41+class HTTPTransport(httpcore.SyncHTTPTransport):42+ def __init__(43+ self,44+ verify: VerifyTypes = True,45+ cert: CertTypes = None,46+ http2: bool = False,47+ limits: Limits = DEFAULT_LIMITS,48+ trust_env: bool = True,49+ proxy: Proxy = None,50+ uds: str = None,51+ local_address: str = None,52+ retries: int = 0,53+ backend: str = "sync",54+ ) -> None:55+ ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)56+57+ if proxy is None:58+ self._pool = httpcore.SyncConnectionPool(59+ ssl_context=ssl_context,60+ max_connections=limits.max_connections,61+ max_keepalive_connections=limits.max_keepalive_connections,62+ keepalive_expiry=limits.keepalive_expiry,63+ http2=http2,64+ uds=uds,65+ local_address=local_address,66+ retries=retries,67+ backend=backend,68+ )69+ else:70+ self._pool = httpcore.SyncHTTPProxy(71+ proxy_url=proxy.url.raw,72+ proxy_headers=proxy.headers.raw,73+ proxy_mode=proxy.mode,74+ ssl_context=ssl_context,75+ max_connections=limits.max_connections,76+ max_keepalive_connections=limits.max_keepalive_connections,77+ keepalive_expiry=limits.keepalive_expiry,78+ http2=http2,79+ backend=backend,80+ )81+82+ def __enter__(self: T) -> T: # Use generics for subclass support.83+ self._pool.__enter__()84+ return self85+86+ def __exit__(87+ self,88+ exc_type: typing.Type[BaseException] = None,89+ exc_value: BaseException = None,90+ traceback: TracebackType = None,91+ ) -> None:92+ self._pool.__exit__(exc_type, exc_value, traceback)93+94+ def request(95+ self,96+ method: bytes,97+ url: URL,98+ headers: Headers = None,99+ stream: httpcore.SyncByteStream = None,100+ ext: dict = None,101+ ) -> typing.Tuple[int, Headers, httpcore.SyncByteStream, dict]:102+ return self._pool.request(method, url, headers=headers, stream=stream, ext=ext)103+104+ def close(self) -> None:105+ self._pool.close()106+107+108+class AsyncHTTPTransport(httpcore.AsyncHTTPTransport):109+ def __init__(110+ self,111+ verify: VerifyTypes = True,112+ cert: CertTypes = None,113+ http2: bool = False,114+ limits: Limits = DEFAULT_LIMITS,115+ trust_env: bool = True,116+ proxy: Proxy = None,117+ uds: str = None,118+ local_address: str = None,119+ retries: int = 0,120+ backend: str = "auto",121+ ) -> None:122+ ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)123+124+ if proxy is None:125+ self._pool = httpcore.AsyncConnectionPool(126+ ssl_context=ssl_context,127+ max_connections=limits.max_connections,128+ max_keepalive_connections=limits.max_keepalive_connections,129+ keepalive_expiry=limits.keepalive_expiry,130+ http2=http2,131+ uds=uds,132+ local_address=local_address,133+ retries=retries,134+ backend=backend,135+ )136+ else:137+ self._pool = httpcore.AsyncHTTPProxy(138+ proxy_url=proxy.url.raw,139+ proxy_headers=proxy.headers.raw,140+ proxy_mode=proxy.mode,141+ ssl_context=ssl_context,142+ max_connections=limits.max_connections,143+ max_keepalive_connections=limits.max_keepalive_connections,144+ keepalive_expiry=limits.keepalive_expiry,145+ http2=http2,146+ backend=backend,147+ )148+149+ async def __aenter__(self: A) -> A: # Use generics for subclass support.150+ await self._pool.__aenter__()151+ return self152+153+ async def __aexit__(154+ self,155+ exc_type: typing.Type[BaseException] = None,156+ exc_value: BaseException = None,157+ traceback: TracebackType = None,158+ ) -> None:159+ await self._pool.__aexit__(exc_type, exc_value, traceback)160+161+ async def arequest(162+ self,163+ method: bytes,164+ url: URL,165+ headers: Headers = None,166+ stream: httpcore.AsyncByteStream = None,167+ ext: dict = None,168+ ) -> typing.Tuple[int, Headers, httpcore.AsyncByteStream, dict]:169+ return await self._pool.arequest(170+ method, url, headers=headers, stream=stream, ext=ext171+ )172+173+ async def aclose(self) -> None:174+ await self._pool.aclose()modified:httpx/__init__.py+3 added
34 unmodified lines35 )36 from ._models import URL, Cookies, Headers, QueryParams, Request, Response37 from ._status_codes import StatusCode, codes38 from ._transports.asgi import ASGITransport39+from ._transports.default import AsyncHTTPTransport, HTTPTransport40 from ._transports.mock import MockTransport41 from ._transports.wsgi import WSGITransport42 43 __all__ = [1 unmodified line45 "__title__",46 "__version__",47 "ASGITransport",48 "AsyncClient",49+ "AsyncHTTPTransport",50 "Auth",51 "BasicAuth",52 "Client",53 "CloseError",10 unmodified lines64 "head",65 "Headers",66 "HTTPError",67 "HTTPStatusError",68+ "HTTPTransport",69 "InvalidURL",70 "Limits",71 "LocalProtocolError",72 "MockTransport",40 unmodified linesmodified:httpx/_client.py+17 added-37 removed
15 unmodified lines16 Limits,17 Proxy,18 Timeout,19 UnsetType,20- create_ssl_context,20 )21 from ._decoders import SUPPORTED_DECODERS22 from ._exceptions import (23 HTTPCORE_EXC_MAP,4 unmodified lines28 )29 from ._models import URL, Cookies, Headers, QueryParams, Request, Response30 from ._status_codes import codes31 from ._transports.asgi import ASGITransport32+from ._transports.default import AsyncHTTPTransport, HTTPTransport33 from ._transports.wsgi import WSGITransport34 from ._types import (35 AuthTypes,36 ByteStream,611 unmodified lines648 649 if app is not None:650 return WSGITransport(app=app)651 652- ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)653-654- return httpcore.SyncConnectionPool(655- ssl_context=ssl_context,656- max_connections=limits.max_connections,657- max_keepalive_connections=limits.max_keepalive_connections,658- keepalive_expiry=limits.keepalive_expiry,659- http2=http2,652+ return HTTPTransport(653+ verify=verify, cert=cert, http2=http2, limits=limits, trust_env=trust_env654 )655 656 def _init_proxy_transport(657 self,3 unmodified lines661 http2: bool = False,662 limits: Limits = DEFAULT_LIMITS,663 trust_env: bool = True,664 ) -> httpcore.SyncHTTPTransport:671- ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)672-673- return httpcore.SyncHTTPProxy(674- proxy_url=proxy.url.raw,675- proxy_headers=proxy.headers.raw,676- proxy_mode=proxy.mode,677- ssl_context=ssl_context,678- max_connections=limits.max_connections,679- max_keepalive_connections=limits.max_keepalive_connections,680- keepalive_expiry=limits.keepalive_expiry,665+ return HTTPTransport(666+ verify=verify,667+ cert=cert,668 http2=http2,669+ limits=limits,670+ trust_env=trust_env,671+ proxy=proxy,672 )673 674 def _transport_for_url(self, url: URL) -> httpcore.SyncHTTPTransport:675 """605 unmodified lines1281 1282 if app is not None:1283 return ASGITransport(app=app)1284 1295- ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)1296-1297- return httpcore.AsyncConnectionPool(1298- ssl_context=ssl_context,1299- max_connections=limits.max_connections,1300- max_keepalive_connections=limits.max_keepalive_connections,1301- keepalive_expiry=limits.keepalive_expiry,1302- http2=http2,1285+ return AsyncHTTPTransport(1286+ verify=verify, cert=cert, http2=http2, limits=limits, trust_env=trust_env1287 )1288 1289 def _init_proxy_transport(1290 self,3 unmodified lines1294 http2: bool = False,1295 limits: Limits = DEFAULT_LIMITS,1296 trust_env: bool = True,1297 ) -> httpcore.AsyncHTTPTransport:1314- ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)1315-1316- return httpcore.AsyncHTTPProxy(1317- proxy_url=proxy.url.raw,1318- proxy_headers=proxy.headers.raw,1319- proxy_mode=proxy.mode,1320- ssl_context=ssl_context,1321- max_connections=limits.max_connections,1322- max_keepalive_connections=limits.max_keepalive_connections,1323- keepalive_expiry=limits.keepalive_expiry,1298+ return AsyncHTTPTransport(1299+ verify=verify,1300+ cert=cert,1301 http2=http2,1302+ limits=limits,1303+ trust_env=trust_env,1304+ proxy=proxy,1305 )1306 1307 def _transport_for_url(self, url: URL) -> httpcore.AsyncHTTPTransport:1308 """528 unmodified linesmodified:tests/client/test_proxies.py+7 added-5 removed
41 unmodified lines42 for proxy_key, url in expected_proxies:43 pattern = URLPattern(proxy_key)44 assert pattern in client._mounts45 proxy = client._mounts[pattern]46+ assert isinstance(proxy, httpx.HTTPTransport)46- assert isinstance(proxy, httpcore.SyncHTTPProxy)47- assert proxy.proxy_origin == url_to_origin(url)47+ assert isinstance(proxy._pool, httpcore.SyncHTTPProxy)48+ assert proxy._pool.proxy_origin == url_to_origin(url)49 50 assert len(expected_proxies) == len(client._mounts)51 52 63 unmodified lines116 117 if expected is None:118 assert transport is client._transport119 else:120+ assert isinstance(transport, httpx.HTTPTransport)119- assert isinstance(transport, httpcore.SyncHTTPProxy)120- assert transport.proxy_origin == url_to_origin(expected)121+ assert isinstance(transport._pool, httpcore.SyncHTTPProxy)122+ assert transport._pool.proxy_origin == url_to_origin(expected)123 124 125 @pytest.mark.asyncio126 async def test_async_proxy_close():124 unmodified lines251 252 if expected is None:253 assert transport == client._transport254 else:253- assert transport.proxy_origin == url_to_origin(expected)255+ assert transport._pool.proxy_origin == url_to_origin(expected)256 257 258 @pytest.mark.parametrize(259 ["proxies", "expected_scheme"],13 unmodified lines