From 8229b34e6112e4cd16d3f4f5bf6ef3028264e33e Mon Sep 17 00:00:00 2001 From: Brian Wellington Date: Fri, 13 Sep 2024 11:33:51 -0700 Subject: [PATCH] Only create httpx transports when needed. (#1130) When a caller passes an httpx client to https(), there's no need to create a transport object that's not used. --- dns/asyncquery.py | 22 +++++++++++----------- dns/query.py | 22 +++++++++++----------- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/dns/asyncquery.py b/dns/asyncquery.py index b93e267d..0848b877 100644 --- a/dns/asyncquery.py +++ b/dns/asyncquery.py @@ -597,7 +597,6 @@ async def https( raise ValueError("session parameter must be an httpx.AsyncClient") wire = q.to_wire() - transport = None headers = {"accept": "application/dns-message"} h1 = http_version in (HTTPVersion.H1, HTTPVersion.DEFAULT) @@ -611,20 +610,21 @@ async def https( else: local_address = source local_port = source_port - transport = backend.get_transport_class()( - local_address=local_address, - http1=h1, - http2=h2, - verify=verify, - local_port=local_port, - bootstrap_address=bootstrap_address, - resolver=resolver, - family=family, - ) if client: cm: contextlib.AbstractAsyncContextManager = NullContext(client) else: + transport = backend.get_transport_class()( + local_address=local_address, + http1=h1, + http2=h2, + verify=verify, + local_port=local_port, + bootstrap_address=bootstrap_address, + resolver=resolver, + family=family, + ) + cm = httpx.AsyncClient(http1=h1, http2=h2, verify=verify, transport=transport) async with cm as the_client: diff --git a/dns/query.py b/dns/query.py index 1880a3f3..b4acf680 100644 --- a/dns/query.py +++ b/dns/query.py @@ -486,7 +486,6 @@ def https( raise ValueError("session parameter must be an httpx.Client") wire = q.to_wire() - transport = None headers = {"accept": "application/dns-message"} h1 = http_version in (HTTPVersion.H1, HTTPVersion.DEFAULT) @@ -500,20 +499,21 @@ def https( else: local_address = the_source[0] local_port = the_source[1] - transport = _HTTPTransport( - local_address=local_address, - http1=h1, - http2=h2, - verify=verify, - local_port=local_port, - bootstrap_address=bootstrap_address, - resolver=resolver, - family=family, - ) if session: cm: contextlib.AbstractContextManager = contextlib.nullcontext(session) else: + transport = _HTTPTransport( + local_address=local_address, + http1=h1, + http2=h2, + verify=verify, + local_port=local_port, + bootstrap_address=bootstrap_address, + resolver=resolver, + family=family, + ) + cm = httpx.Client(http1=h1, http2=h2, verify=verify, transport=transport) with cm as session: # see https://tools.ietf.org/html/rfc8484#section-4.1.1 for DoH -- 2.47.3