From 6d162a0d3a77e986e231c140cfb7971df0b53599 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 8 May 2019 10:47:22 +0100 Subject: [PATCH] Graceful behavior for unclosed HTTPS connections --- httpcore/backends/default.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/httpcore/backends/default.py b/httpcore/backends/default.py index b6acb764..1e8996fb 100644 --- a/httpcore/backends/default.py +++ b/httpcore/backends/default.py @@ -20,6 +20,23 @@ from ..interfaces import BasePoolSemaphore, BaseReader, BaseWriter OptionalTimeout = typing.Optional[TimeoutConfig] +# Monky-patch for https://bugs.python.org/issue36709 +# +# This prevents console errors when outstanding HTTPS connections +# still exist at the point of exiting. +# +# Clients which have been opened using a `with` block, or which have +# had `close()` closed, will not exhibit this issue in the first place. + +_write = asyncio.selector_events._SelectorSocketTransport.write + +def _fixed_write(self, exc): + if not self._loop.is_closed(): + _write(self, exc) + +asyncio.selector_events._SelectorSocketTransport.write = _fixed_write + + class Reader(BaseReader): def __init__( self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig @@ -58,7 +75,7 @@ class Writer(BaseWriter): self.stream_writer.write(data) try: - data = await asyncio.wait_for( # type: ignore + await asyncio.wait_for( # type: ignore self.stream_writer.drain(), timeout.write_timeout ) except asyncio.TimeoutError: @@ -121,6 +138,8 @@ async def connect( if ident is None: ident = ssl_object.selected_npn_protocol() + stream_writer.transport.set_write_buffer_limits(high=0, low=0) + reader = Reader(stream_reader=stream_reader, timeout=timeout) writer = Writer(stream_writer=stream_writer, timeout=timeout) protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11 -- 2.47.3