Add client.request
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parent 9a362c0 · Browse files · 7 files·+107 added−135 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+107 added−135 removed
- tests:+72 added−92 removed
- other:+35 added−43 removed
Provenance
- Commit
275443c- Tree
972754f- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
9a362c0
7 files changed+107 added−135 removed
modified:httpcore/connections.py+2 added-12 removed
15 unmodified lines16 h11.ConnectionClosed,17 ]18 19 20-class Connection:20+class Connection(Client):21 def __init__(22 self,23 origin: typing.Union[str, Origin],24 ssl: SSLConfig = DEFAULT_SSL_CONFIG,17 unmodified lines42 request: Request,43 *,44 ssl: typing.Optional[SSLConfig] = None,45 timeout: typing.Optional[TimeoutConfig] = None,46- stream: bool = False,46 ) -> Response:47 assert request.url.origin == self.origin48 49 if ssl is None:33 unmodified lines83 reason = event.reason.decode("latin1")84 status_code = event.status_code85 headers = event.headers86 body = self._body_iter(timeout)88- response = Response(87+ return Response(88 status_code=status_code,89 reason=reason,90 headers=headers,91 body=body,92 on_close=self._release,93 )94 96- if not stream:97- # Read the response body.98- try:99- await response.read()100- finally:101- await response.close()102-103- return response104-95 async def _connect(self, ssl: SSLConfig, timeout: TimeoutConfig) -> None:96 ssl_context = await ssl.load_ssl_context() if self.origin.is_secure else None97 98 try:65 unmodified linesmodified:httpcore/datastructures.py+19 added-2 removed
1 import http2 import typing3+from types import TracebackType4 from urllib.parse import urlsplit5 6 from .config import SSLConfig, TimeoutConfig7 from .decoders import (243 unmodified lines251 timeout: typing.Optional[TimeoutConfig] = None,252 stream: bool = False,253 ) -> Response:254 request = Request(method, url, headers=headers, body=body)254- return await self.send(request, ssl=ssl, timeout=timeout, stream=stream)255+ response = await self.send(request, ssl=ssl, timeout=timeout)256+ if not stream:257+ try:258+ await response.read()259+ finally:260+ await response.close()261+ return response262 263 async def send(264 self,265 request: Request,266 *,267 ssl: typing.Optional[SSLConfig] = None,268 timeout: typing.Optional[TimeoutConfig] = None,262- stream: bool = False,269 ) -> Response:270 raise NotImplementedError() # pragma: nocover271 272 async def close(self) -> None:273 raise NotImplementedError() # pragma: nocover274+275+ async def __aenter__(self) -> "Client":276+ return self277+278+ async def __aexit__(279+ self,280+ exc_type: typing.Type[BaseException] = None,281+ exc_value: BaseException = None,282+ traceback: TracebackType = None,283+ ) -> None:284+ await self.close()modified:httpcore/pool.py+14 added-29 removed
1 import asyncio2 import typing3-from types import TracebackType3 4 from .config import (5 DEFAULT_CA_BUNDLE_PATH,6 DEFAULT_POOL_LIMITS,7 unmodified lines14 from .datastructures import Client, Origin, Request, Response15 from .exceptions import PoolTimeout16 17 19-class ConnectionSemaphore:20- def __init__(self, max_connections: int = None):21- if max_connections is not None:22- self.semaphore = asyncio.BoundedSemaphore(value=max_connections)23-24- async def acquire(self) -> None:25- if hasattr(self, "semaphore"):26- await self.semaphore.acquire()27-28- def release(self) -> None:29- if hasattr(self, "semaphore"):30- self.semaphore.release()31-32-33-class ConnectionPool:18+class ConnectionPool(Client):19 def __init__(20 self,21 *,22 ssl: SSLConfig = DEFAULT_SSL_CONFIG,18 unmodified lines41 request: Request,42 *,43 ssl: typing.Optional[SSLConfig] = None,44 timeout: typing.Optional[TimeoutConfig] = None,60- stream: bool = False,45 ) -> Response:46 connection = await self.acquire_connection(request.url.origin, timeout=timeout)63- response = await connection.send(64- request, ssl=ssl, timeout=timeout, stream=stream65- )47+ response = await connection.send(request, ssl=ssl, timeout=timeout)48 return response49 50 @property51 def num_connections(self) -> int:50 unmodified lines102 103 async def close(self) -> None:104 self.is_closed = True105 124- async def __aenter__(self) -> "ConnectionPool":125- return self106 127- async def __aexit__(128- self,129- exc_type: typing.Type[BaseException] = None,130- exc_value: BaseException = None,131- traceback: TracebackType = None,132- ) -> None:133- await self.close()107+class ConnectionSemaphore:108+ def __init__(self, max_connections: int = None):109+ if max_connections is not None:110+ self.semaphore = asyncio.BoundedSemaphore(value=max_connections)111+112+ async def acquire(self) -> None:113+ if hasattr(self, "semaphore"):114+ await self.semaphore.acquire()115+116+ def release(self) -> None:117+ if hasattr(self, "semaphore"):118+ self.semaphore.release()modified:tests/test_api.py+10 added-12 removed
3 unmodified lines4 5 6 @pytest.mark.asyncio7 async def test_get(server):8- async with httpcore.ConnectionPool() as client:9- request = httpcore.Request("GET", "http://127.0.0.1:8000/")10- response = await client.send(request)8+ async with httpcore.ConnectionPool() as http:9+ response = await http.request("GET", "http://127.0.0.1:8000/")10 assert response.status_code == 20011 assert response.body == b"Hello, world!"12 13 14 @pytest.mark.asyncio15 async def test_post(server):17- async with httpcore.ConnectionPool() as client:18- request = httpcore.Request(16+ async with httpcore.ConnectionPool() as http:17+ response = await http.request(18 "POST", "http://127.0.0.1:8000/", body=b"Hello, world!"19 )21- response = await client.send(request)20 assert response.status_code == 20021 22 23 @pytest.mark.asyncio24 async def test_stream_response(server):27- async with httpcore.ConnectionPool() as client:28- request = httpcore.Request("GET", "http://127.0.0.1:8000/")29- response = await client.send(request, stream=True)25+ async with httpcore.ConnectionPool() as http:26+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)27 assert response.status_code == 20028 assert not hasattr(response, "body")29 body = await response.read()30 assert body == b"Hello, world!"4 unmodified lines35 async def hello_world():36 yield b"Hello, "37 yield b"world!"38 42- async with httpcore.ConnectionPool() as client:43- request = httpcore.Request("POST", "http://127.0.0.1:8000/", body=hello_world())44- response = await client.send(request)39+ async with httpcore.ConnectionPool() as http:40+ response = await http.request(41+ "POST", "http://127.0.0.1:8000/", body=hello_world()42+ )43 assert response.status_code == 200modified:tests/test_connections.py+5 added-7 removed
3 unmodified lines4 5 6 @pytest.mark.asyncio7 async def test_get(server):8- client = httpcore.Connection(origin="http://127.0.0.1:8000/")9- request = httpcore.Request(method="GET", url="http://127.0.0.1:8000/")10- response = await client.send(request)8+ http = httpcore.Connection(origin="http://127.0.0.1:8000/")9+ response = await http.request("GET", "http://127.0.0.1:8000/")10 assert response.status_code == 20011 assert response.body == b"Hello, world!"12 13 14 @pytest.mark.asyncio15 async def test_post(server):17- client = httpcore.Connection(origin="http://127.0.0.1:8000/")18- request = httpcore.Request(19- method="POST", url="http://127.0.0.1:8000/", body=b"Hello, world!"16+ http = httpcore.Connection(origin="http://127.0.0.1:8000/")17+ response = await http.request(18+ "POST", "http://127.0.0.1:8000/", body=b"Hello, world!"19 )21- response = await client.send(request)20 assert response.status_code == 200modified:tests/test_pool.py+50 added-62 removed
6 unmodified lines7 async def test_keepalive_connections(server):8 """9 Connections should default to staying in a keep-alive state.10 """11- async with httpcore.ConnectionPool() as client:12- request = httpcore.Request("GET", "http://127.0.0.1:8000/")13- response = await client.send(request)14- assert client.num_active_connections == 015- assert client.num_keepalive_connections == 111+ async with httpcore.ConnectionPool() as http:12+ response = await http.request("GET", "http://127.0.0.1:8000/")13+ assert http.num_active_connections == 014+ assert http.num_keepalive_connections == 115 17- request = httpcore.Request("GET", "http://127.0.0.1:8000/")18- response = await client.send(request)19- assert client.num_active_connections == 020- assert client.num_keepalive_connections == 116+ response = await http.request("GET", "http://127.0.0.1:8000/")17+ assert http.num_active_connections == 018+ assert http.num_keepalive_connections == 119 20 21 @pytest.mark.asyncio22 async def test_differing_connection_keys(server):23 """24 Connnections to differing connection keys should result in multiple connections.25 """28- async with httpcore.ConnectionPool() as client:29- request = httpcore.Request("GET", "http://127.0.0.1:8000/")30- response = await client.send(request)31- assert client.num_active_connections == 032- assert client.num_keepalive_connections == 126+ async with httpcore.ConnectionPool() as http:27+ response = await http.request("GET", "http://127.0.0.1:8000/")28+ assert http.num_active_connections == 029+ assert http.num_keepalive_connections == 130 34- request = httpcore.Request("GET", "http://localhost:8000/")35- response = await client.send(request)36- assert client.num_active_connections == 037- assert client.num_keepalive_connections == 231+ response = await http.request("GET", "http://localhost:8000/")32+ assert http.num_active_connections == 033+ assert http.num_keepalive_connections == 234 35 36 @pytest.mark.asyncio37 async def test_soft_limit(server):1 unmodified line39 The soft_limit config should limit the maximum number of keep-alive connections.40 """41 limits = httpcore.PoolLimits(soft_limit=1)42 47- async with httpcore.ConnectionPool(limits=limits) as client:48- request = httpcore.Request("GET", "http://127.0.0.1:8000/")49- response = await client.send(request)50- assert client.num_active_connections == 051- assert client.num_keepalive_connections == 143+ async with httpcore.ConnectionPool(limits=limits) as http:44+ response = await http.request("GET", "http://127.0.0.1:8000/")45+ assert http.num_active_connections == 046+ assert http.num_keepalive_connections == 147 53- request = httpcore.Request("GET", "http://localhost:8000/")54- response = await client.send(request)55- assert client.num_active_connections == 056- assert client.num_keepalive_connections == 148+ response = await http.request("GET", "http://localhost:8000/")49+ assert http.num_active_connections == 050+ assert http.num_keepalive_connections == 151 52 53 @pytest.mark.asyncio54 async def test_streaming_response_holds_connection(server):55 """56 A streaming request should hold the connection open until the response is read.57 """64- async with httpcore.ConnectionPool() as client:65- request = httpcore.Request("GET", "http://127.0.0.1:8000/")66- response = await client.send(request, stream=True)67- assert client.num_active_connections == 168- assert client.num_keepalive_connections == 058+ async with httpcore.ConnectionPool() as http:59+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)60+ assert http.num_active_connections == 161+ assert http.num_keepalive_connections == 062 63 await response.read()64 72- assert client.num_active_connections == 073- assert client.num_keepalive_connections == 165+ assert http.num_active_connections == 066+ assert http.num_keepalive_connections == 167 68 69 @pytest.mark.asyncio70 async def test_multiple_concurrent_connections(server):71 """72 Multiple conncurrent requests should open multiple conncurrent connections.73 """81- async with httpcore.ConnectionPool() as client:82- request = httpcore.Request("GET", "http://127.0.0.1:8000/")83- response_a = await client.send(request, stream=True)84- assert client.num_active_connections == 185- assert client.num_keepalive_connections == 074+ async with httpcore.ConnectionPool() as http:75+ response_a = await http.request("GET", "http://127.0.0.1:8000/", stream=True)76+ assert http.num_active_connections == 177+ assert http.num_keepalive_connections == 078 87- request = httpcore.Request("GET", "http://127.0.0.1:8000/")88- response_b = await client.send(request, stream=True)89- assert client.num_active_connections == 290- assert client.num_keepalive_connections == 079+ response_b = await http.request("GET", "http://127.0.0.1:8000/", stream=True)80+ assert http.num_active_connections == 281+ assert http.num_keepalive_connections == 082 83 await response_b.read()93- assert client.num_active_connections == 194- assert client.num_keepalive_connections == 184+ assert http.num_active_connections == 185+ assert http.num_keepalive_connections == 186 87 await response_a.read()97- assert client.num_active_connections == 098- assert client.num_keepalive_connections == 288+ assert http.num_active_connections == 089+ assert http.num_keepalive_connections == 290 91 92 @pytest.mark.asyncio93 async def test_close_connections(server):94 """95 Using a `Connection: close` header should close the connection.96 """97 headers = [(b"connection", b"close")]107- async with httpcore.ConnectionPool() as client:108- request = httpcore.Request("GET", "http://127.0.0.1:8000/", headers=headers)109- response = await client.send(request)110- assert client.num_active_connections == 0111- assert client.num_keepalive_connections == 098+ async with httpcore.ConnectionPool() as http:99+ response = await http.request("GET", "http://127.0.0.1:8000/", headers=headers)100+ assert http.num_active_connections == 0101+ assert http.num_keepalive_connections == 0102 103 104 @pytest.mark.asyncio105 async def test_standard_response_close(server):106 """107 A standard close should keep the connection open.108 """119- async with httpcore.ConnectionPool() as client:120- request = httpcore.Request("GET", "http://127.0.0.1:8000/")121- response = await client.send(request, stream=True)109+ async with httpcore.ConnectionPool() as http:110+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)111 await response.read()112 await response.close()124- assert client.num_active_connections == 0125- assert client.num_keepalive_connections == 1113+ assert http.num_active_connections == 0114+ assert http.num_keepalive_connections == 1115 116 117 @pytest.mark.asyncio118 async def test_premature_response_close(server):119 """120 A premature close should close the connection.121 """133- async with httpcore.ConnectionPool() as client:134- request = httpcore.Request("GET", "http://127.0.0.1:8000/")135- response = await client.send(request, stream=True)122+ async with httpcore.ConnectionPool() as http:123+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)124 await response.close()137- assert client.num_active_connections == 0138- assert client.num_keepalive_connections == 0125+ assert http.num_active_connections == 0126+ assert http.num_keepalive_connections == 0modified:tests/test_timeouts.py+7 added-11 removed
5 unmodified lines6 @pytest.mark.asyncio7 async def test_read_timeout(server):8 timeout = httpcore.TimeoutConfig(read_timeout=0.0001)9 10- async with httpcore.ConnectionPool(timeout=timeout) as client:10+ async with httpcore.ConnectionPool(timeout=timeout) as http:11 with pytest.raises(httpcore.ReadTimeout):12- request = httpcore.Request("GET", "http://127.0.0.1:8000/slow_response")13- await client.send(request)12+ await http.request("GET", "http://127.0.0.1:8000/slow_response")13 14 15 @pytest.mark.asyncio16 async def test_connect_timeout(server):17 timeout = httpcore.TimeoutConfig(connect_timeout=0.0001)18 20- async with httpcore.ConnectionPool(timeout=timeout) as client:19+ async with httpcore.ConnectionPool(timeout=timeout) as http:20 with pytest.raises(httpcore.ConnectTimeout):21 # See https://stackoverflow.com/questions/100841/23- request = httpcore.Request("GET", "http://10.255.255.1/")24- await client.send(request)22+ await http.request("GET", "http://10.255.255.1/")23 24 25 @pytest.mark.asyncio26 async def test_pool_timeout(server):27 timeout = httpcore.TimeoutConfig(pool_timeout=0.0001)28 limits = httpcore.PoolLimits(hard_limit=1)29 32- async with httpcore.ConnectionPool(timeout=timeout, limits=limits) as client:33- request = httpcore.Request("GET", "http://127.0.0.1:8000/")34- response = await client.send(request, stream=True)30+ async with httpcore.ConnectionPool(timeout=timeout, limits=limits) as http:31+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)32 33 with pytest.raises(httpcore.PoolTimeout):37- request = httpcore.Request("GET", "http://127.0.0.1:8000/")38- await client.send(request)34+ await http.request("GET", "http://127.0.0.1:8000/")35 36 await response.read()