Skip to content
Myr

Add SyncConnectionPool

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 39eb55b · Browse files · 6 files+182 added−5 removed
This commit

State

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

Diff stats

6 files+182 added−5 removed

  • tests:+38 added−0 removed
  • other:+144 added−5 removed

6 files+182 added−5 removed

modified:httpcore/__init__.py+1 added
9 unmodified lines
10 StreamConsumed,11 Timeout,12)13from .pool import ConnectionPool14from .sync import SyncClient, SyncConnectionPool1516__version__ = "0.1.1"
added:httpcore/compat.py+51 added
1import asyncio23if hasattr(asyncio, "run"):4 asyncio_run = asyncio.run5else: # pragma: nocover67 def asyncio_run(main, *, debug=False): # type: ignore8 if asyncio._get_running_loop() is not None:9 raise RuntimeError(10 "asyncio.run() cannot be called from a running event loop"11 )1213 if not asyncio.iscoroutine(main):14 raise ValueError("a coroutine was expected, got {!r}".format(main))1516 loop = asyncio.new_event_loop()17 try:18 asyncio.set_event_loop(loop)19 loop.set_debug(debug)20 return loop.run_until_complete(main)21 finally:22 try:23 _cancel_all_tasks(loop)24 loop.run_until_complete(loop.shutdown_asyncgens())25 finally:26 asyncio.set_event_loop(None)27 loop.close()2829 def _cancel_all_tasks(loop): # type: ignore30 to_cancel = asyncio.all_tasks(loop)31 if not to_cancel:32 return3334 for task in to_cancel:35 task.cancel()3637 loop.run_until_complete(38 tasks.gather(*to_cancel, loop=loop, return_exceptions=True)39 )4041 for task in to_cancel:42 if task.cancelled():43 continue44 if task.exception() is not None:45 loop.call_exception_handler(46 {47 "message": "unhandled exception during asyncio.run() shutdown",48 "exception": task.exception(),49 "task": task,50 }51 )
modified:httpcore/datastructures.py+1 added-1 removed
99 unmodified lines
100 *,101 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),102 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",103 ):104 self.method = method104 self.method = method.upper()105 self.url = URL(url) if isinstance(url, str) else url106 self.headers = list(headers)107 if isinstance(body, bytes):108 self.is_streaming = False
176 unmodified lines
modified:httpcore/pool.py+12 added-4 removed
104 unmodified lines
105106107class ConnectionSemaphore:108 def __init__(self, max_connections: int = None):109 if max_connections is not None:110 self.semaphore = asyncio.BoundedSemaphore(value=max_connections)109 self.max_connections = max_connections110111 @property112 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:113 if not hasattr(self, "_semaphore"):114 if self.max_connections is None:115 self._semaphore = None116 else:117 self._semaphore = asyncio.BoundedSemaphore(value=self.max_connections)118 return self._semaphore119120 async def acquire(self) -> None:113 if hasattr(self, "semaphore"):121 if self.semaphore is not None:122 await self.semaphore.acquire()123124 def release(self) -> None:117 if hasattr(self, "semaphore"):125 if self.semaphore is not None:126 self.semaphore.release()
modified:httpcore/sync.py+79 added
1import typing2from types import TracebackType34from .compat import asyncio_run5from .config import SSLConfig, TimeoutConfig6from .datastructures import URL, Client, Response7from .pool import ConnectionPool8910class SyncResponse:11 def __init__(self, response: Response):12 self._response = response1314 @property15 def status_code(self) -> int:16 return self._response.status_code1718 @property19 def reason(self) -> str:20 return self._response.reason2122 @property23 def headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:24 return self._response.headers2526 @property27 def body(self) -> bytes:28 return self._response.body2930 def read(self) -> bytes:31 return asyncio_run(self._response.read())323334class SyncClient:35 def __init__(self, client: Client):36 self._client = client3738 def request(39 self,40 method: str,41 url: typing.Union[str, URL],42 *,43 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),44 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",45 ssl: typing.Optional[SSLConfig] = None,46 timeout: typing.Optional[TimeoutConfig] = None,47 stream: bool = False,48 ) -> SyncResponse:49 response = asyncio_run(50 self._client.request(51 method,52 url,53 headers=headers,54 body=body,55 ssl=ssl,56 timeout=timeout,57 stream=stream,58 )59 )60 return SyncResponse(response)6162 def close(self) -> None:63 asyncio_run(self._client.close())6465 def __enter__(self) -> "SyncClient":66 return self6768 def __exit__(69 self,70 exc_type: typing.Type[BaseException] = None,71 exc_value: BaseException = None,72 traceback: TracebackType = None,73 ) -> None:74 self.close()757677def SyncConnectionPool(*args: typing.Any, **kwargs: typing.Any) -> SyncClient:78 client = ConnectionPool(*args, **kwargs) # type: ignore79 return SyncClient(client)
added:tests/test_sync.py+38 added
1import asyncio2import functools34import pytest56import httpcore789def threadpool(func):10 """11 Our sync tests should run in seperate thread to the uvicorn server.12 """1314 @functools.wraps(func)15 async def wrapped(*args, **kwargs):16 nonlocal func1718 loop = asyncio.get_event_loop()19 if kwargs:20 func = functools.partial(func, **kwargs)21 await loop.run_in_executor(None, func, *args)2223 return pytest.mark.asyncio(wrapped)242526@threadpool27def test_get(server):28 with httpcore.SyncConnectionPool() as http:29 response = http.request("GET", "http://127.0.0.1:8000/")30 assert response.status_code == 20031 assert response.body == b"Hello, world!"323334@threadpool35def test_post(server):36 with httpcore.SyncConnectionPool() as http:37 response = http.request("POST", "http://127.0.0.1:8000/", body=b"Hello, world!")38 assert response.status_code == 200