Skip to content
Myr

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

6 files+242 added−70 removed

modified:docs/advanced.md+28 added-28 removed
969 unmodified lines
970971### Usage972973For some advanced configuration you might need to instantiate a transport974class directly, and pass it to the client instance. The `httpcore` package975provides a `local_address` configuration that is only available via this976low-level API.974class directly, and pass it to the client instance. One example is the975`local_address` configuration which is only available via this low-level API.976977```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```982991Similarly, `httpcore` provides a `uds` option for connecting via a Unix Domain Socket that is only available via this low-level API:983Connection retries are also available via this interface.984993```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```990991Similarly, instantiating a transport directly provides a `uds` option for992connecting via a Unix Domain Socket that is only available via this low-level API:993994```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```10031009Unlike the `httpx.Client()`, the lower-level `httpcore` transport instances1010do not include any default values for configuring aspects such as the1011connection pooling details, so you'll need to provide more explicit1012configuration when using this API.10131004### urllib3 transport10051006This [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 lines
1110```11111112A couple of other sketches of how you might take advantage of mounted transports...11131114Disabling HTTP/2 on a single given domain...11151116```python1117mounts = {1118 "all://": httpx.HTTPTransport(http2=True),1119 "all://*example.org": httpx.HTTPTransport()1120}1121client = httpx.Client(mounts=mounts)1122```11231124Mocking requests to a given domain:11251126```python1127# All requests to "example.org" should be mocked out.
15 unmodified lines
modified:docs/async.md+13 added
110 unmodified lines
111112await client.post(url, data=upload_bytes())113```114115### Explicit transport instances116117When instantiating a transport instance directly, you need to use `httpx.AsyncHTTPTransport`.118119For instance:120121```pycon122>>> import httpx123>>> transport = httpx.AsyncHTTPTransport(retries=1)124>>> async with httpx.AsyncClient(transport=transport) as client:125>>> ...126```127128## Supported async environments129130HTTPX supports either `asyncio` or `trio` as an async environment.131
108 unmodified lines
added:httpx/_transports/default.py+174 added
1"""2Custom transports, with nicely configured defaults.34The following additional keyword arguments are currently supported by httpcore...56* uds: str7* local_address: str8* retries: int9* backend: str ("auto", "asyncio", "trio", "curio", "anyio", "sync")1011Example usages...1213# Disable HTTP/2 on a single specfic domain.14mounts = {15 "all://": httpx.HTTPTransport(http2=True),16 "all://*example.org": httpx.HTTPTransport()17}1819# Using advanced httpcore configuration, with connection retries.20transport = httpx.HTTPTransport(retries=1)21client = httpx.Client(transport=transport)2223# Using advanced httpcore configuration, with unix domain sockets.24transport = httpx.HTTPTransport(uds="socket.uds")25client = httpx.Client(transport=transport)26"""27import typing28from types import TracebackType2930import httpcore3132from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context33from .._types import CertTypes, VerifyTypes3435T = typing.TypeVar("T", bound="HTTPTransport")36A = typing.TypeVar("A", bound="AsyncHTTPTransport")37Headers = typing.List[typing.Tuple[bytes, bytes]]38URL = typing.Tuple[bytes, bytes, typing.Optional[int], bytes]394041class 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)5657 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 )8182 def __enter__(self: T) -> T: # Use generics for subclass support.83 self._pool.__enter__()84 return self8586 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)9394 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)103104 def close(self) -> None:105 self._pool.close()106107108class 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)123124 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 )148149 async def __aenter__(self: A) -> A: # Use generics for subclass support.150 await self._pool.__aenter__()151 return self152153 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)160161 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 )172173 async def aclose(self) -> None:174 await self._pool.aclose()
modified:httpx/__init__.py+3 added
34 unmodified lines
35)36from ._models import URL, Cookies, Headers, QueryParams, Request, Response37from ._status_codes import StatusCode, codes38from ._transports.asgi import ASGITransport39from ._transports.default import AsyncHTTPTransport, HTTPTransport40from ._transports.mock import MockTransport41from ._transports.wsgi import WSGITransport4243__all__ = [
1 unmodified line
45 "__title__",46 "__version__",47 "ASGITransport",48 "AsyncClient",49 "AsyncHTTPTransport",50 "Auth",51 "BasicAuth",52 "Client",53 "CloseError",
10 unmodified lines
64 "head",65 "Headers",66 "HTTPError",67 "HTTPStatusError",68 "HTTPTransport",69 "InvalidURL",70 "Limits",71 "LocalProtocolError",72 "MockTransport",
40 unmodified lines
modified:httpx/_client.py+17 added-37 removed
15 unmodified lines
16 Limits,17 Proxy,18 Timeout,19 UnsetType,20 create_ssl_context,20)21from ._decoders import SUPPORTED_DECODERS22from ._exceptions import (23 HTTPCORE_EXC_MAP,
4 unmodified lines
28)29from ._models import URL, Cookies, Headers, QueryParams, Request, Response30from ._status_codes import codes31from ._transports.asgi import ASGITransport32from ._transports.default import AsyncHTTPTransport, HTTPTransport33from ._transports.wsgi import WSGITransport34from ._types import (35 AuthTypes,36 ByteStream,
611 unmodified lines
648649 if app is not None:650 return WSGITransport(app=app)651652 ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)653654 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 )655656 def _init_proxy_transport(657 self,
3 unmodified lines
661 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)672673 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 )673674 def _transport_for_url(self, url: URL) -> httpcore.SyncHTTPTransport:675 """
605 unmodified lines
12811282 if app is not None:1283 return ASGITransport(app=app)12841295 ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)12961297 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 )12881289 def _init_proxy_transport(1290 self,
3 unmodified lines
1294 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)13151316 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 )13061307 def _transport_for_url(self, url: URL) -> httpcore.AsyncHTTPTransport:1308 """
528 unmodified lines
modified:tests/client/test_proxies.py+7 added-5 removed
41 unmodified lines
42 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)4950 assert len(expected_proxies) == len(client._mounts)5152
63 unmodified lines
116117 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)123124125@pytest.mark.asyncio126async def test_async_proxy_close():
124 unmodified lines
251252 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)256257258@pytest.mark.parametrize(259 ["proxies", "expected_scheme"],
13 unmodified lines