Merge pull request #17 from encode/close-keepalive-connections
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Close outstanding connections on pool.close()
authored by Tom Christie · committed by GitHub · parents 0c20fba, 4ed3a8a · Browse files · 7 files·+40 added−66 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+40 added−66 removed
- other:+40 added−66 removed
Provenance
- Commit
91a2a1b- Tree
20f6e8c- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent 1
0c20fba- Parent 2
4ed3a8a
7 files changed+40 added−66 removed
modified:httpcore/__init__.py+2 added-2 removed
1 from .config import PoolLimits, SSLConfig, TimeoutConfig2 from .connectionpool import ConnectionPool3 from .datastructures import URL, Origin, Request, Response4 from .exceptions import (5- BadResponse,5 ConnectTimeout,6 PoolTimeout,7+ ProtocolError,8 ReadTimeout,9 ResponseClosed,10 StreamConsumed,11 Timeout,12 )13 from .http11 import HTTP11Connection14 from .sync import SyncClient, SyncConnectionPool15 16-__version__ = "0.2.0"16+__version__ = "0.2.1"deleted:httpcore/compat.py-52 removed
1-import asyncio2-3-if hasattr(asyncio, "run"):4- asyncio_run = asyncio.run5-6-else: # pragma: nocover7-8- def asyncio_run(main, *, debug=False): # type: ignore9- if asyncio._get_running_loop() is not None:10- raise RuntimeError(11- "asyncio.run() cannot be called from a running event loop"12- )13-14- if not asyncio.iscoroutine(main):15- raise ValueError("a coroutine was expected, got {!r}".format(main))16-17- loop = asyncio.new_event_loop()18- try:19- asyncio.set_event_loop(loop)20- loop.set_debug(debug)21- return loop.run_until_complete(main)22- finally:23- try:24- _cancel_all_tasks(loop)25- loop.run_until_complete(loop.shutdown_asyncgens())26- finally:27- asyncio.set_event_loop(None)28- loop.close()29-30- def _cancel_all_tasks(loop): # type: ignore31- to_cancel = asyncio.all_tasks(loop)32- if not to_cancel:33- return34-35- for task in to_cancel:36- task.cancel()37-38- loop.run_until_complete(39- tasks.gather(*to_cancel, loop=loop, return_exceptions=True)40- )41-42- for task in to_cancel:43- if task.cancelled():44- continue45- if task.exception() is not None:46- loop.call_exception_handler(47- {48- "message": "unhandled exception during asyncio.run() shutdown",49- "exception": task.exception(),50- "task": task,51- }52- )modified:httpcore/connectionpool.py+7 added-1 removed
8 unmodified lines9 PoolLimits,10 SSLConfig,11 TimeoutConfig,12 )13-from .http11 import HTTP11Connection13 from .datastructures import Client, Origin, Request, Response14 from .exceptions import PoolTimeout15+from .http11 import HTTP11Connection16 17 18 class ConnectionPool(Client):19 def __init__(81 unmodified lines101 self._keepalive_connections[connection.origin] = [connection]102 103 async def close(self) -> None:104 self.is_closed = True105+ all_connections = []106+ for connections in self._keepalive_connections.values():107+ all_connections.extend(list(connections))108+ self._keepalive_connections.clear()109+ for connection in all_connections:110+ await connection.close()111 112 113 class ConnectionSemaphore:114 def __init__(self, max_connections: int = None):18 unmodified linesmodified:httpcore/exceptions.py+2 added-2 removed
20 unmodified lines21 Timeout while waiting to acquire a connection from the pool.22 """23 24 25-class BadResponse(Exception):25+class ProtocolError(Exception):26 """27- A malformed HTTP response.27+ Malformed HTTP.28 """29 30 31 class StreamConsumed(Exception):11 unmodified linesmodified:httpcore/sync.py+10 added-8 removed
1+import asyncio2 import typing3 from types import TracebackType4 4-from .compat import asyncio_run5 from .config import SSLConfig, TimeoutConfig6 from .connectionpool import ConnectionPool7 from .datastructures import URL, Client, Response8 9 10 class SyncResponse:11- def __init__(self, response: Response):11+ def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):12 self._response = response13+ self._loop = loop14 15 @property16 def status_code(self) -> int:17 return self._response.status_code10 unmodified lines28 def body(self) -> bytes:29 return self._response.body30 31 def read(self) -> bytes:31- return asyncio_run(self._response.read())32+ return self._loop.run_until_complete(self._response.read())33 34 def stream(self) -> typing.Iterator[bytes]:35 inner = self._response.stream()36 while True:37 try:37- yield asyncio_run(inner.__anext__())38+ yield self._loop.run_until_complete(inner.__anext__())39 except StopAsyncIteration as exc:40 break41 42 def close(self) -> None:42- return asyncio_run(self._response.close())43+ return self._loop.run_until_complete(self._response.close())44 45 46 class SyncClient:47 def __init__(self, client: Client):48 self._client = client49+ self._loop = asyncio.new_event_loop()50 51 def request(52 self,53 method: str,4 unmodified lines58 ssl: typing.Optional[SSLConfig] = None,59 timeout: typing.Optional[TimeoutConfig] = None,60 stream: bool = False,61 ) -> SyncResponse:60- response = asyncio_run(62+ response = self._loop.run_until_complete(63 self._client.request(64 method,65 url,66 headers=headers,2 unmodified lines69 timeout=timeout,70 stream=stream,71 )72 )71- return SyncResponse(response)73+ return SyncResponse(response, self._loop)74 75 def close(self) -> None:74- asyncio_run(self._client.close())76+ self._loop.run_until_complete(self._client.close())77 78 def __enter__(self) -> "SyncClient":79 return self80 12 unmodified linesadded:.travis.yml+19 added
12345678910111213141516171819sudo: requireddist: xeniallanguage: python
cache: pip
python: - "3.6" - "3.7"
install: - pip install -U -r requirements.txt
script: - scripts/test
after_script: - pip install codecov - codecovmodified:requirements.txt-1 removed
6 unmodified lines7 8 # Testing9 autoflake10 black11-codecov11 isort12 mypy13 pytest14 pytest-asyncio2 unmodified lines