Skip to content

Commit 6a02e81

Browse files
adamtheturtleclaude
andcommitted
Use shared httpx.Client in HTTPXTransport for connection pooling
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent c4439cf commit 6a02e81

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

src/vws/transports.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,26 @@ class HTTPXTransport:
9797
9898
Use this transport for environments where ``httpx`` is
9999
preferred over ``requests``.
100+
A single ``httpx.Client`` is reused across requests
101+
for connection pooling.
100102
"""
101103

104+
def __init__(self) -> None:
105+
"""Create an ``HTTPXTransport``."""
106+
self._client = httpx.Client()
107+
108+
def close(self) -> None:
109+
"""Close the underlying ``httpx.Client``."""
110+
self._client.close()
111+
112+
def __enter__(self) -> Self:
113+
"""Enter the context manager."""
114+
return self
115+
116+
def __exit__(self, *_args: object) -> None:
117+
"""Exit the context manager and close the client."""
118+
self.close()
119+
102120
def __call__(
103121
self,
104122
*,
@@ -136,7 +154,7 @@ def __call__(
136154
pool=None,
137155
)
138156

139-
httpx_response = httpx.request(
157+
httpx_response = self._client.request(
140158
method=method,
141159
url=url,
142160
headers=headers,

tests/test_transports.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,28 @@ def test_tuple_timeout() -> None:
6161
assert isinstance(response, Response)
6262
assert response.status_code == HTTPStatus.OK
6363

64+
@staticmethod
65+
@respx.mock
66+
def test_context_manager() -> None:
67+
"""``HTTPXTransport`` can be used as a context manager."""
68+
route = respx.post(url="https://example.com/test").mock(
69+
return_value=httpx.Response(
70+
status_code=HTTPStatus.OK,
71+
text="OK",
72+
),
73+
)
74+
with HTTPXTransport() as transport:
75+
response = transport(
76+
method="POST",
77+
url="https://example.com/test",
78+
headers={"Content-Type": "text/plain"},
79+
data=b"hello",
80+
request_timeout=30.0,
81+
)
82+
assert route.called
83+
assert isinstance(response, Response)
84+
assert response.status_code == HTTPStatus.OK
85+
6486

6587
class TestAsyncHTTPXTransport:
6688
"""Tests for ``AsyncHTTPXTransport``."""

0 commit comments

Comments
 (0)