sync.py
This file
Path
httpcore/sync.py
87 lines · 2.4 KiB · Python
Last changed by
Add idna support. More tests.Tom Christiebefore adoptionb948798
History of this fileTake it
1import asyncio2import typing3from types import TracebackType45from .config import SSLConfig, TimeoutConfig6from .dispatch.connection_pool import ConnectionPool7from .interfaces import Adapter8from .models import URL, Headers, Response91011class SyncResponse:12 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):13 self._response = response14 self._loop = loop1516 @property17 def status_code(self) -> int:18 return self._response.status_code1920 @property21 def reason_phrase(self) -> str:22 return self._response.reason_phrase2324 @property25 def headers(self) -> Headers:26 return self._response.headers2728 @property29 def content(self) -> bytes:30 return self._response.content3132 @property33 def text(self) -> str:34 return self._response.text3536 def read(self) -> bytes:37 return self._loop.run_until_complete(self._response.read())3839 def stream(self) -> typing.Iterator[bytes]:40 inner = self._response.stream()41 while True:42 try:43 yield self._loop.run_until_complete(inner.__anext__())44 except StopAsyncIteration as exc:45 break4647 def close(self) -> None:48 return self._loop.run_until_complete(self._response.close())495051class SyncClient:52 def __init__(self, adapter: Adapter):53 self._client = adapter54 self._loop = asyncio.new_event_loop()5556 def request(57 self,58 method: str,59 url: typing.Union[str, URL],60 *,61 headers: typing.List[typing.Tuple[bytes, bytes]] = [],62 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",63 **options: typing.Any64 ) -> SyncResponse:65 response = self._loop.run_until_complete(66 self._client.request(method, url, headers=headers, body=body, **options)67 )68 return SyncResponse(response, self._loop)6970 def close(self) -> None:71 self._loop.run_until_complete(self._client.close())7273 def __enter__(self) -> "SyncClient":74 return self7576 def __exit__(77 self,78 exc_type: typing.Type[BaseException] = None,79 exc_value: BaseException = None,80 traceback: TracebackType = None,81 ) -> None:82 self.close()838485def SyncConnectionPool(*args: typing.Any, **kwargs: typing.Any) -> SyncClient:86 client = ConnectionPool(*args, **kwargs) # type: ignore87 return SyncClient(client)