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
Provenance
- Commit
903a961- Tree
4918459- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent 1
39eb55b- Parent 2
e58d255
6 files changed+215 added−6 removed
modified:httpcore/__init__.py+2 added-1 removed
9 unmodified lines10 StreamConsumed,11 Timeout,12 )13 from .pool import ConnectionPool14+from .sync import SyncClient, SyncConnectionPool15 15-__version__ = "0.1.1"16+__version__ = "0.2.0"added:httpcore/compat.py+51 added
1+import asyncio2+3+if hasattr(asyncio, "run"):4+ asyncio_run = asyncio.run5+else: # pragma: nocover6+7+ 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+ )12+13+ if not asyncio.iscoroutine(main):14+ raise ValueError("a coroutine was expected, got {!r}".format(main))15+16+ 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()28+29+ def _cancel_all_tasks(loop): # type: ignore30+ to_cancel = asyncio.all_tasks(loop)31+ if not to_cancel:32+ return33+34+ for task in to_cancel:35+ task.cancel()36+37+ loop.run_until_complete(38+ tasks.gather(*to_cancel, loop=loop, return_exceptions=True)39+ )40+41+ 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 lines100 *,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 = False176 unmodified linesmodified:httpcore/pool.py+12 added-4 removed
104 unmodified lines105 106 107 class 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_connections110 111+ @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._semaphore119+120 async def acquire(self) -> None:113- if hasattr(self, "semaphore"):121+ if self.semaphore is not None:122 await self.semaphore.acquire()123 124 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
1+import typing2+from types import TracebackType3+4+from .compat import asyncio_run5+from .config import SSLConfig, TimeoutConfig6+from .datastructures import URL, Client, Response7+from .pool import ConnectionPool8+9+10+class SyncResponse:11+ def __init__(self, response: Response):12+ self._response = response13+14+ @property15+ def status_code(self) -> int:16+ return self._response.status_code17+18+ @property19+ def reason(self) -> str:20+ return self._response.reason21+22+ @property23+ def headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:24+ return self._response.headers25+26+ @property27+ def body(self) -> bytes:28+ return self._response.body29+30+ def read(self) -> bytes:31+ return asyncio_run(self._response.read())32+33+ 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+ break40+41+ def close(self) -> None:42+ return asyncio_run(self._response.close())43+44+45+class SyncClient:46+ def __init__(self, client: Client):47+ self._client = client48+49+ 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)72+73+ def close(self) -> None:74+ asyncio_run(self._client.close())75+76+ def __enter__(self) -> "SyncClient":77+ return self78+79+ 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()86+87+88+def 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
1+import asyncio2+import functools3+4+import pytest5+6+import httpcore7+8+9+def threadpool(func):10+ """11+ Our sync tests should run in seperate thread to the uvicorn server.12+ """13+14+ @functools.wraps(func)15+ async def wrapped(*args, **kwargs):16+ nonlocal func17+18+ loop = asyncio.get_event_loop()19+ if kwargs:20+ func = functools.partial(func, **kwargs)21+ await loop.run_in_executor(None, func, *args)22+23+ return pytest.mark.asyncio(wrapped)24+25+26+@threadpool27+def 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!"32+33+34+@threadpool35+def 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 == 20039+40+41+@threadpool42+def 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!"49+50+51+@threadpool52+def 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!"