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
Provenance
- Commit
6a4376b- Tree
6207593- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
fcc1fe1
5 files changed+251 added−170 removed
modified:httpcore/api.py+4 added-74 removed
7 unmodified lines8 PoolLimits,9 SSLConfig,10 TimeoutConfig,11 )12-from .decoders import IdentityDecoder13-from .exceptions import ResponseClosed, StreamConsumed12+from .models import Response13 14 15 async def request(16 method: str,3 unmodified lines20 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 lines48 *,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()54 55 async def close(self) -> None:56 self.is_closed = True57 6 unmodified lines64 exc_value: BaseException = None,65 traceback: TracebackType = None,66 ) -> None:67 await self.close()74-75-76-class 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 = body96-97- 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.body107-108- 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()119-120- 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()132-133- 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
1+from config import TimeoutConfig2+3+import asyncio4+import h115+import ssl6+7+8+class Connection:9+ def __init__(self):10+ self.reader = None11+ self.writer = None12+ self.state = h11.Connection(our_role=h11.CLIENT)13+14+ 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()21+22+ async def send(self, request: Request) -> Response:23+ method = request.method24+25+ target = request.url.path26+ if request.url.query:27+ target += "?" + request.url.query28+29+ headers = [30+ ("host", request.url.netloc)31+ ] += request.headers32+33+ # Send the request method, path/query, and headers.34+ event = h11.Request(method=method, target=target, headers=headers)35+ await self._send_event(event)36+37+ # 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)45+46+ # Finalize sending the request.47+ event = h11.EndOfMessage()48+ await connection.send_event(event)49+50+ async def _send_event(self, message):51+ data = self.state.send(message)52+ self.writer.write(data)53+54+ async def _receive_event(self, timeout):55+ event = self.state.next_event()56+57+ 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()64+65+ return event66+67+ 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
1+import typing2+3+from .decoders import IdentityDecoder4+from .exceptions import ResponseClosed, StreamConsumed5+6+7+class 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 = body27+28+ 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.body38+39+ 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()50+51+ 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()63+64+ 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
1-import pytest2-3-import httpcore4-5-6-@pytest.mark.asyncio7-async 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_closed12-13-14-@pytest.mark.asyncio15-async def test_read_response():16- response = await httpcore.request("GET", "http://example.com")17-18- assert response.status_code == 20019- assert response.body == b"Hello, world!"20- assert response.is_closed21-22- body = await response.read()23-24- assert body == b"Hello, world!"25- assert response.body == b"Hello, world!"26- assert response.is_closed27-28-29-@pytest.mark.asyncio30-async def test_stream_response():31- response = await httpcore.request("GET", "http://example.com")32-33- assert response.status_code == 20034- assert response.body == b"Hello, world!"35- assert response.is_closed36-37- body = b''38- async for part in response.stream():39- body += part40-41- assert body == b"Hello, world!"42- assert response.body == b"Hello, world!"43- assert response.is_closed44-45-46-@pytest.mark.asyncio47-async def test_read_streaming_response():48- response = await httpcore.request("GET", "http://example.com", stream=True)49-50- assert response.status_code == 20051- assert not hasattr(response, 'body')52- assert not response.is_closed53-54- body = await response.read()55-56- assert body == b"Hello, world!"57- assert response.body == b"Hello, world!"58- assert response.is_closed59-60-61-@pytest.mark.asyncio62-async def test_stream_streaming_response():63- response = await httpcore.request("GET", "http://example.com", stream=True)64-65- assert response.status_code == 20066- assert not hasattr(response, 'body')67- assert not response.is_closed68-69- body = b''70- async for part in response.stream():71- body += part72-73- assert body == b"Hello, world!"74- assert not hasattr(response, 'body')75- assert response.is_closed76-77-78-@pytest.mark.asyncio79-async def test_cannot_read_after_stream_consumed():80- response = await httpcore.request("GET", "http://example.com", stream=True)81-82- body = b''83- async for part in response.stream():84- body += part85-86- with pytest.raises(httpcore.StreamConsumed):87- await response.read()88-89-@pytest.mark.asyncio90-async def test_cannot_read_after_response_closed():91- response = await httpcore.request("GET", "http://example.com", stream=True)92-93- await response.close()94-95- with pytest.raises(httpcore.ResponseClosed):96- await response.read()added:tests/test_responses.py+109 added
1+import pytest2+3+import httpcore4+5+6+class 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!")14+15+16+http = MockRequests()17+18+19+@pytest.mark.asyncio20+async 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_closed25+26+27+@pytest.mark.asyncio28+async def test_read_response():29+ response = await http.request("GET", "http://example.com")30+31+ assert response.status_code == 20032+ assert response.body == b"Hello, world!"33+ assert response.is_closed34+35+ body = await response.read()36+37+ assert body == b"Hello, world!"38+ assert response.body == b"Hello, world!"39+ assert response.is_closed40+41+42+@pytest.mark.asyncio43+async def test_stream_response():44+ response = await http.request("GET", "http://example.com")45+46+ assert response.status_code == 20047+ assert response.body == b"Hello, world!"48+ assert response.is_closed49+50+ body = b''51+ async for part in response.stream():52+ body += part53+54+ assert body == b"Hello, world!"55+ assert response.body == b"Hello, world!"56+ assert response.is_closed57+58+59+@pytest.mark.asyncio60+async def test_read_streaming_response():61+ response = await http.request("GET", "http://example.com", stream=True)62+63+ assert response.status_code == 20064+ assert not hasattr(response, 'body')65+ assert not response.is_closed66+67+ body = await response.read()68+69+ assert body == b"Hello, world!"70+ assert response.body == b"Hello, world!"71+ assert response.is_closed72+73+74+@pytest.mark.asyncio75+async def test_stream_streaming_response():76+ response = await http.request("GET", "http://example.com", stream=True)77+78+ assert response.status_code == 20079+ assert not hasattr(response, 'body')80+ assert not response.is_closed81+82+ body = b''83+ async for part in response.stream():84+ body += part85+86+ assert body == b"Hello, world!"87+ assert not hasattr(response, 'body')88+ assert response.is_closed89+90+91+@pytest.mark.asyncio92+async def test_cannot_read_after_stream_consumed():93+ response = await http.request("GET", "http://example.com", stream=True)94+95+ body = b''96+ async for part in response.stream():97+ body += part98+99+ with pytest.raises(httpcore.StreamConsumed):100+ await response.read()101+102+@pytest.mark.asyncio103+async def test_cannot_read_after_response_closed():104+ response = await http.request("GET", "http://example.com", stream=True)105+106+ await response.close()107+108+ with pytest.raises(httpcore.ResponseClosed):109+ await response.read()