Skip to content
Myr

Connections

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 fcc1fe1 · Browse files · 5 files+251 added−170 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+251 added−170 removed

  • tests:+109 added−96 removed
  • other:+142 added−74 removed

5 files+251 added−170 removed

modified:httpcore/api.py+4 added-74 removed
7 unmodified lines
8 PoolLimits,9 SSLConfig,10 TimeoutConfig,11)12from .decoders import IdentityDecoder13from .exceptions import ResponseClosed, StreamConsumed12from .models import Response131415async def request(16 method: str,
3 unmodified lines
20 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",21 stream: bool = False,22 ssl: SSLConfig = DEFAULT_SSL_CONFIG,23 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,25) -> "Response":24) -> Response:25 async with PoolManager(ssl=ssl, timeout=timeout) as pool:26 return await pool.request(27 method=method, url=url, headers=headers, body=body, stream=stream28 )
19 unmodified lines
48 *,49 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),50 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",51 stream: bool = False,53 ) -> "Response":54 if stream:55 async def streaming_body():56 yield b"Hello, "57 yield b"world!"58 return Response(200, body=streaming_body)59 return Response(200, body=b"Hello, world!")52 ) -> Response:53 raise NotImplementedError()5455 async def close(self) -> None:56 self.is_closed = True57
6 unmodified lines
64 exc_value: BaseException = None,65 traceback: TracebackType = None,66 ) -> None:67 await self.close()747576class Response:77 def __init__(78 self,79 status_code: int,80 *,81 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),82 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",83 on_close: typing.Callable = None,84 ):85 self.status_code = status_code86 self.headers = list(headers)87 self.on_close = on_close88 self.is_closed = False89 self.is_streamed = False90 self.decoder = IdentityDecoder()91 if isinstance(body, bytes):92 self.is_closed = True93 self.body = body94 else:95 self.body_aiter = body9697 async def read(self) -> bytes:98 """99 Read and return the response content.100 """101 if not hasattr(self, "body"):102 body = b""103 async for part in self.stream():104 body += part105 self.body = body106 return self.body107108 async def stream(self):109 """110 A byte-iterator over the decoded response content.111 This will allow us to handle gzip, deflate, and brotli encoded responses.112 """113 if hasattr(self, "body"):114 yield self.body115 else:116 async for chunk in self.raw():117 yield self.decoder.decode(chunk)118 yield self.decoder.flush()119120 async def raw(self) -> typing.AsyncIterator[bytes]:121 """122 A byte-iterator over the raw response content.123 """124 if self.is_streamed:125 raise StreamConsumed()126 if self.is_closed:127 raise ResponseClosed()128 self.is_streamed = True129 async for part in self.body_aiter():130 yield part131 await self.close()132133 async def close(self) -> None:134 if not self.is_closed:135 self.is_closed = True136 if self.on_close is not None:137 await self.on_close()
added:httpcore/connections.py+70 added
1from config import TimeoutConfig23import asyncio4import h115import ssl678class Connection:9 def __init__(self):10 self.reader = None11 self.writer = None12 self.state = h11.Connection(our_role=h11.CLIENT)1314 async def open(self, host: str, port: int, ssl: ssl.SSLContext):15 try:16 self.reader, self.writer = await asyncio.wait_for(17 asyncio.open_connection(host, port, ssl=ssl), timeout18 )19 except asyncio.TimeoutError:20 raise ConnectTimeout()2122 async def send(self, request: Request) -> Response:23 method = request.method2425 target = request.url.path26 if request.url.query:27 target += "?" + request.url.query2829 headers = [30 ("host", request.url.netloc)31 ] += request.headers3233 # Send the request method, path/query, and headers.34 event = h11.Request(method=method, target=target, headers=headers)35 await self._send_event(event)3637 # Send the request body.38 if request.is_streaming:39 async for data in request.raw():40 event = h11.Data(data=data)41 await self._send_event(event)42 else:43 event = h11.Data(data=request.body)44 await self._send_event(event)4546 # Finalize sending the request.47 event = h11.EndOfMessage()48 await connection.send_event(event)4950 async def _send_event(self, message):51 data = self.state.send(message)52 self.writer.write(data)5354 async def _receive_event(self, timeout):55 event = self.state.next_event()5657 while type(event) is h11.NEED_DATA:58 try:59 data = await asyncio.wait_for(self.reader.read(2048), timeout)60 except asyncio.TimeoutError:61 raise ReadTimeout()62 self.state.receive_data(data)63 event = self.state.next_event()6465 return event6667 async def close(self):68 self.writer.close()69 if hasattr(self.writer, "wait_closed"):70 await self.writer.wait_closed()
added:httpcore/models.py+68 added
1import typing23from .decoders import IdentityDecoder4from .exceptions import ResponseClosed, StreamConsumed567class Response:8 def __init__(9 self,10 status_code: int,11 *,12 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),13 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",14 on_close: typing.Callable = None,15 ):16 self.status_code = status_code17 self.headers = list(headers)18 self.on_close = on_close19 self.is_closed = False20 self.is_streamed = False21 self.decoder = IdentityDecoder()22 if isinstance(body, bytes):23 self.is_closed = True24 self.body = body25 else:26 self.body_aiter = body2728 async def read(self) -> bytes:29 """30 Read and return the response content.31 """32 if not hasattr(self, "body"):33 body = b""34 async for part in self.stream():35 body += part36 self.body = body37 return self.body3839 async def stream(self):40 """41 A byte-iterator over the decoded response content.42 This will allow us to handle gzip, deflate, and brotli encoded responses.43 """44 if hasattr(self, "body"):45 yield self.body46 else:47 async for chunk in self.raw():48 yield self.decoder.decode(chunk)49 yield self.decoder.flush()5051 async def raw(self) -> typing.AsyncIterator[bytes]:52 """53 A byte-iterator over the raw response content.54 """55 if self.is_streamed:56 raise StreamConsumed()57 if self.is_closed:58 raise ResponseClosed()59 self.is_streamed = True60 async for part in self.body_aiter():61 yield part62 await self.close()6364 async def close(self) -> None:65 if not self.is_closed:66 self.is_closed = True67 if self.on_close is not None:68 await self.on_close()
modified:tests/test_api.py-96 removed
1import pytest23import httpcore456@pytest.mark.asyncio7async def test_request():8 response = await httpcore.request("GET", "http://example.com")9 assert response.status_code == 20010 assert response.body == b"Hello, world!"11 assert response.is_closed121314@pytest.mark.asyncio15async def test_read_response():16 response = await httpcore.request("GET", "http://example.com")1718 assert response.status_code == 20019 assert response.body == b"Hello, world!"20 assert response.is_closed2122 body = await response.read()2324 assert body == b"Hello, world!"25 assert response.body == b"Hello, world!"26 assert response.is_closed272829@pytest.mark.asyncio30async def test_stream_response():31 response = await httpcore.request("GET", "http://example.com")3233 assert response.status_code == 20034 assert response.body == b"Hello, world!"35 assert response.is_closed3637 body = b''38 async for part in response.stream():39 body += part4041 assert body == b"Hello, world!"42 assert response.body == b"Hello, world!"43 assert response.is_closed444546@pytest.mark.asyncio47async def test_read_streaming_response():48 response = await httpcore.request("GET", "http://example.com", stream=True)4950 assert response.status_code == 20051 assert not hasattr(response, 'body')52 assert not response.is_closed5354 body = await response.read()5556 assert body == b"Hello, world!"57 assert response.body == b"Hello, world!"58 assert response.is_closed596061@pytest.mark.asyncio62async def test_stream_streaming_response():63 response = await httpcore.request("GET", "http://example.com", stream=True)6465 assert response.status_code == 20066 assert not hasattr(response, 'body')67 assert not response.is_closed6869 body = b''70 async for part in response.stream():71 body += part7273 assert body == b"Hello, world!"74 assert not hasattr(response, 'body')75 assert response.is_closed767778@pytest.mark.asyncio79async def test_cannot_read_after_stream_consumed():80 response = await httpcore.request("GET", "http://example.com", stream=True)8182 body = b''83 async for part in response.stream():84 body += part8586 with pytest.raises(httpcore.StreamConsumed):87 await response.read()8889@pytest.mark.asyncio90async def test_cannot_read_after_response_closed():91 response = await httpcore.request("GET", "http://example.com", stream=True)9293 await response.close()9495 with pytest.raises(httpcore.ResponseClosed):96 await response.read()
added:tests/test_responses.py+109 added
1import pytest23import httpcore456class MockRequests(httpcore.PoolManager):7 async def request(self, method, url, *, headers = (), body = b'', stream = False) -> httpcore.Response:8 if stream:9 async def streaming_body():10 yield b"Hello, "11 yield b"world!"12 return httpcore.Response(200, body=streaming_body)13 return httpcore.Response(200, body=b"Hello, world!")141516http = MockRequests()171819@pytest.mark.asyncio20async def test_request():21 response = await http.request("GET", "http://example.com")22 assert response.status_code == 20023 assert response.body == b"Hello, world!"24 assert response.is_closed252627@pytest.mark.asyncio28async def test_read_response():29 response = await http.request("GET", "http://example.com")3031 assert response.status_code == 20032 assert response.body == b"Hello, world!"33 assert response.is_closed3435 body = await response.read()3637 assert body == b"Hello, world!"38 assert response.body == b"Hello, world!"39 assert response.is_closed404142@pytest.mark.asyncio43async def test_stream_response():44 response = await http.request("GET", "http://example.com")4546 assert response.status_code == 20047 assert response.body == b"Hello, world!"48 assert response.is_closed4950 body = b''51 async for part in response.stream():52 body += part5354 assert body == b"Hello, world!"55 assert response.body == b"Hello, world!"56 assert response.is_closed575859@pytest.mark.asyncio60async def test_read_streaming_response():61 response = await http.request("GET", "http://example.com", stream=True)6263 assert response.status_code == 20064 assert not hasattr(response, 'body')65 assert not response.is_closed6667 body = await response.read()6869 assert body == b"Hello, world!"70 assert response.body == b"Hello, world!"71 assert response.is_closed727374@pytest.mark.asyncio75async def test_stream_streaming_response():76 response = await http.request("GET", "http://example.com", stream=True)7778 assert response.status_code == 20079 assert not hasattr(response, 'body')80 assert not response.is_closed8182 body = b''83 async for part in response.stream():84 body += part8586 assert body == b"Hello, world!"87 assert not hasattr(response, 'body')88 assert response.is_closed899091@pytest.mark.asyncio92async def test_cannot_read_after_stream_consumed():93 response = await http.request("GET", "http://example.com", stream=True)9495 body = b''96 async for part in response.stream():97 body += part9899 with pytest.raises(httpcore.StreamConsumed):100 await response.read()101102@pytest.mark.asyncio103async def test_cannot_read_after_response_closed():104 response = await http.request("GET", "http://example.com", stream=True)105106 await response.close()107108 with pytest.raises(httpcore.ResponseClosed):109 await response.read()