Skip to content
Myr

Merge pull request #13 from encode/sync

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

Add SyncConnectionPool

authored by Tom Christie · committed by GitHub · parents 39eb55b, e58d255 · Browse files · 6 files+215 added−6 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+215 added−6 removed

  • tests:+59 added−0 removed
  • other:+156 added−6 removed

6 files+215 added−6 removed

modified:httpcore/__init__.py+2 added-1 removed
9 unmodified lines
10 StreamConsumed,11 Timeout,12)13from .pool import ConnectionPool14from .sync import SyncClient, SyncConnectionPool1515__version__ = "0.1.1"16__version__ = "0.2.0"
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+90 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())3233 def stream(self) -> typing.Iterator[bytes]:34 inner = self._response.stream()35 while True:36 try:37 yield asyncio_run(inner.__anext__())38 except StopAsyncIteration as exc:39 break4041 def close(self) -> None:42 return asyncio_run(self._response.close())434445class SyncClient:46 def __init__(self, client: Client):47 self._client = client4849 def request(50 self,51 method: str,52 url: typing.Union[str, URL],53 *,54 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),55 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",56 ssl: typing.Optional[SSLConfig] = None,57 timeout: typing.Optional[TimeoutConfig] = None,58 stream: bool = False,59 ) -> SyncResponse:60 response = asyncio_run(61 self._client.request(62 method,63 url,64 headers=headers,65 body=body,66 ssl=ssl,67 timeout=timeout,68 stream=stream,69 )70 )71 return SyncResponse(response)7273 def close(self) -> None:74 asyncio_run(self._client.close())7576 def __enter__(self) -> "SyncClient":77 return self7879 def __exit__(80 self,81 exc_type: typing.Type[BaseException] = None,82 exc_value: BaseException = None,83 traceback: TracebackType = None,84 ) -> None:85 self.close()868788def SyncConnectionPool(*args: typing.Any, **kwargs: typing.Any) -> SyncClient:89 client = ConnectionPool(*args, **kwargs) # type: ignore90 return SyncClient(client)
added:tests/test_sync.py+59 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 == 200394041@threadpool42def test_stream_response(server):43 with httpcore.SyncConnectionPool() as http:44 response = http.request("GET", "http://127.0.0.1:8000/", stream=True)45 assert response.status_code == 20046 assert not hasattr(response, "body")47 body = response.read()48 assert body == b"Hello, world!"495051@threadpool52def test_stream_iterator(server):53 with httpcore.SyncConnectionPool() as http:54 response = http.request("GET", "http://127.0.0.1:8000/", stream=True)55 assert response.status_code == 20056 body = b''57 for chunk in response.stream():58 body += chunk59 assert body == b"Hello, world!"