Skip to content

Commit

Permalink
Only create httpx transports when needed. (#1130)
Browse files Browse the repository at this point in the history
When a caller passes an httpx client to https(), there's no need to
create a transport object that's not used.
  • Loading branch information
bwelling authored Sep 13, 2024
1 parent 2007e43 commit 8229b34
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 22 deletions.
22 changes: 11 additions & 11 deletions dns/asyncquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand Down
22 changes: 11 additions & 11 deletions dns/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down

0 comments on commit 8229b34

Please sign in to comment.