Refactor interfaces (#252)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Move Dispatcher, AsyncDispatcher into dispatch/base.py * Move concurrency interfaces into concurrency/base.py
authored by Tom Christie · committed by Florimond Manca · parent 4ea4af6 · Browse files · 13 files·+300 added−293 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+300 added−293 removed
- other:+300 added−293 removed
Provenance
- Commit
c0554e9- Tree
02e5f24- Author
Tom Christie <tom@tomchristie.com>- Committer
Florimond Manca <florimond.manca@gmail.com>- Parent
4ea4af6
13 files changed+300 added−293 removed
modified:httpx/concurrency/asyncio.py+4 added-35 removed
12 unmodified lines13 import ssl14 import typing15 from types import TracebackType16 17-from ..config import PoolLimits, TimeoutConfig18-from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19-from ..interfaces import (17+from .base import (18 BaseBackgroundManager,19 BasePoolSemaphore,20 BaseQueue,21 BaseReader,22 BaseWriter,23 ConcurrencyBackend,24+ TimeoutFlag,25 )26+from ..config import PoolLimits, TimeoutConfig27+from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout28 29 SSL_MONKEY_PATCH_APPLIED = False30 31 17 unmodified lines49 50 MonkeyPatch.write = _fixed_write51 52 52-class TimeoutFlag:53- """54- A timeout flag holds a state of either read-timeout or write-timeout mode.55-56- We use this so that we can attempt both reads and writes concurrently, while57- only enforcing timeouts in one direction.58-59- During a request/response cycle we start in write-timeout mode.60-61- Once we've sent a request fully, or once we start seeing a response,62- then we switch to read-timeout mode instead.63- """64-65- def __init__(self) -> None:66- self.raise_on_read_timeout = False67- self.raise_on_write_timeout = True68-69- def set_read_timeouts(self) -> None:70- """71- Set the flag to read-timeout mode.72- """73- self.raise_on_read_timeout = True74- self.raise_on_write_timeout = False75-76- def set_write_timeouts(self) -> None:77- """78- Set the flag to write-timeout mode.79- """80- self.raise_on_read_timeout = False81- self.raise_on_write_timeout = True82-83-53 class Reader(BaseReader):54 def __init__(55 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig56 ) -> None:190 unmodified linesadded:httpx/concurrency/base.py+164 added
1+import ssl2+import typing3+from types import TracebackType4+5+from ..config import PoolLimits, TimeoutConfig6+7+8+class TimeoutFlag:9+ """10+ A timeout flag holds a state of either read-timeout or write-timeout mode.11+12+ We use this so that we can attempt both reads and writes concurrently, while13+ only enforcing timeouts in one direction.14+15+ During a request/response cycle we start in write-timeout mode.16+17+ Once we've sent a request fully, or once we start seeing a response,18+ then we switch to read-timeout mode instead.19+ """20+21+ def __init__(self) -> None:22+ self.raise_on_read_timeout = False23+ self.raise_on_write_timeout = True24+25+ def set_read_timeouts(self) -> None:26+ """27+ Set the flag to read-timeout mode.28+ """29+ self.raise_on_read_timeout = True30+ self.raise_on_write_timeout = False31+32+ def set_write_timeouts(self) -> None:33+ """34+ Set the flag to write-timeout mode.35+ """36+ self.raise_on_read_timeout = False37+ self.raise_on_write_timeout = True38+39+40+class BaseReader:41+ """42+ A stream reader. Abstracts away any asyncio-specific interfaces43+ into a more generic base class, that we can use with alternate44+ backend, or for stand-alone test cases.45+ """46+47+ async def read(48+ self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None49+ ) -> bytes:50+ raise NotImplementedError() # pragma: no cover51+52+ def is_connection_dropped(self) -> bool:53+ raise NotImplementedError() # pragma: no cover54+55+56+class BaseWriter:57+ """58+ A stream writer. Abstracts away any asyncio-specific interfaces59+ into a more generic base class, that we can use with alternate60+ backend, or for stand-alone test cases.61+ """62+63+ def write_no_block(self, data: bytes) -> None:64+ raise NotImplementedError() # pragma: no cover65+66+ async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:67+ raise NotImplementedError() # pragma: no cover68+69+ async def close(self) -> None:70+ raise NotImplementedError() # pragma: no cover71+72+73+class BaseQueue:74+ """75+ A FIFO queue. Abstracts away any asyncio-specific interfaces.76+ """77+78+ async def get(self) -> typing.Any:79+ raise NotImplementedError() # pragma: no cover80+81+ async def put(self, value: typing.Any) -> None:82+ raise NotImplementedError() # pragma: no cover83+84+85+class BasePoolSemaphore:86+ """87+ A semaphore for use with connection pooling.88+89+ Abstracts away any asyncio-specific interfaces.90+ """91+92+ async def acquire(self) -> None:93+ raise NotImplementedError() # pragma: no cover94+95+ def release(self) -> None:96+ raise NotImplementedError() # pragma: no cover97+98+99+class ConcurrencyBackend:100+ async def connect(101+ self,102+ hostname: str,103+ port: int,104+ ssl_context: typing.Optional[ssl.SSLContext],105+ timeout: TimeoutConfig,106+ ) -> typing.Tuple[BaseReader, BaseWriter, str]:107+ raise NotImplementedError() # pragma: no cover108+109+ def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:110+ raise NotImplementedError() # pragma: no cover111+112+ async def run_in_threadpool(113+ self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any114+ ) -> typing.Any:115+ raise NotImplementedError() # pragma: no cover116+117+ async def iterate_in_threadpool(self, iterator): # type: ignore118+ class IterationComplete(Exception):119+ pass120+121+ def next_wrapper(iterator): # type: ignore122+ try:123+ return next(iterator)124+ except StopIteration:125+ raise IterationComplete()126+127+ while True:128+ try:129+ yield await self.run_in_threadpool(next_wrapper, iterator)130+ except IterationComplete:131+ break132+133+ def run(134+ self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any135+ ) -> typing.Any:136+ raise NotImplementedError() # pragma: no cover137+138+ def iterate(self, async_iterator): # type: ignore139+ while True:140+ try:141+ yield self.run(async_iterator.__anext__)142+ except StopAsyncIteration:143+ break144+145+ def create_queue(self, max_size: int) -> BaseQueue:146+ raise NotImplementedError() # pragma: no cover147+148+ def background_manager(149+ self, coroutine: typing.Callable, args: typing.Any150+ ) -> "BaseBackgroundManager":151+ raise NotImplementedError() # pragma: no cover152+153+154+class BaseBackgroundManager:155+ async def __aenter__(self) -> "BaseBackgroundManager":156+ raise NotImplementedError() # pragma: no cover157+158+ async def __aexit__(159+ self,160+ exc_type: typing.Type[BaseException] = None,161+ exc_value: BaseException = None,162+ traceback: TracebackType = None,163+ ) -> None:164+ raise NotImplementedError() # pragma: no covermodified:httpx/dispatch/asgi.py+2 added-1 removed
1 import asyncio2 import typing3 4+from .base import AsyncDispatcher5+from ..concurrency.base import ConcurrencyBackend6 from ..concurrency.asyncio import AsyncioBackend7 from ..config import CertTypes, TimeoutTypes, VerifyTypes6-from ..interfaces import AsyncDispatcher, ConcurrencyBackend8 from ..models import AsyncRequest, AsyncResponse9 10 11 class ASGIDispatch(AsyncDispatcher):185 unmodified linesadded:httpx/dispatch/base.py+111 added
1+import typing2+from types import TracebackType3+4+from ..config import CertTypes, TimeoutTypes, VerifyTypes5+from ..models import (6+ AsyncRequest,7+ AsyncRequestData,8+ AsyncResponse,9+ HeaderTypes,10+ QueryParamTypes,11+ Request,12+ RequestData,13+ Response,14+ URLTypes,15+)16+17+18+class AsyncDispatcher:19+ """20+ Base class for async dispatcher classes, that handle sending the request.21+22+ Stubs out the interface, as well as providing a `.request()` convenience23+ implementation, to make it easy to use or test stand-alone dispatchers,24+ without requiring a complete `Client` instance.25+ """26+27+ async def request(28+ self,29+ method: str,30+ url: URLTypes,31+ *,32+ data: AsyncRequestData = b"",33+ params: QueryParamTypes = None,34+ headers: HeaderTypes = None,35+ verify: VerifyTypes = None,36+ cert: CertTypes = None,37+ timeout: TimeoutTypes = None,38+ ) -> AsyncResponse:39+ request = AsyncRequest(method, url, data=data, params=params, headers=headers)40+ return await self.send(request, verify=verify, cert=cert, timeout=timeout)41+42+ async def send(43+ self,44+ request: AsyncRequest,45+ verify: VerifyTypes = None,46+ cert: CertTypes = None,47+ timeout: TimeoutTypes = None,48+ ) -> AsyncResponse:49+ raise NotImplementedError() # pragma: nocover50+51+ async def close(self) -> None:52+ pass # pragma: nocover53+54+ async def __aenter__(self) -> "AsyncDispatcher":55+ return self56+57+ async def __aexit__(58+ self,59+ exc_type: typing.Type[BaseException] = None,60+ exc_value: BaseException = None,61+ traceback: TracebackType = None,62+ ) -> None:63+ await self.close()64+65+66+class Dispatcher:67+ """68+ Base class for synchronous dispatcher classes, that handle sending the request.69+70+ Stubs out the interface, as well as providing a `.request()` convenience71+ implementation, to make it easy to use or test stand-alone dispatchers,72+ without requiring a complete `Client` instance.73+ """74+75+ def request(76+ self,77+ method: str,78+ url: URLTypes,79+ *,80+ data: RequestData = b"",81+ params: QueryParamTypes = None,82+ headers: HeaderTypes = None,83+ verify: VerifyTypes = None,84+ cert: CertTypes = None,85+ timeout: TimeoutTypes = None,86+ ) -> Response:87+ request = Request(method, url, data=data, params=params, headers=headers)88+ return self.send(request, verify=verify, cert=cert, timeout=timeout)89+90+ def send(91+ self,92+ request: Request,93+ verify: VerifyTypes = None,94+ cert: CertTypes = None,95+ timeout: TimeoutTypes = None,96+ ) -> Response:97+ raise NotImplementedError() # pragma: nocover98+99+ def close(self) -> None:100+ pass # pragma: nocover101+102+ def __enter__(self) -> "Dispatcher":103+ return self104+105+ def __exit__(106+ self,107+ exc_type: typing.Type[BaseException] = None,108+ exc_value: BaseException = None,109+ traceback: TracebackType = None,110+ ) -> None:111+ self.close()modified:httpx/dispatch/connection_pool.py+2 added-1 removed
1 import typing2 3+from .base import AsyncDispatcher4 from ..concurrency.asyncio import AsyncioBackend5+from ..concurrency.base import ConcurrencyBackend6 from ..config import (7 DEFAULT_POOL_LIMITS,8 DEFAULT_TIMEOUT_CONFIG,9 CertTypes,1 unmodified line11 PoolLimits,12 TimeoutTypes,13 VerifyTypes,14 )13-from ..interfaces import AsyncDispatcher, ConcurrencyBackend15 from ..models import AsyncRequest, AsyncResponse, Origin16 from .connection import HTTPConnection17 18 CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]151 unmodified linesmodified:httpx/dispatch/connection.py+2 added-1 removed
1 import functools2 import ssl3 import typing4 5+from .base import AsyncDispatcher6 from ..concurrency.asyncio import AsyncioBackend7+from ..concurrency.base import ConcurrencyBackend8 from ..config import (9 DEFAULT_TIMEOUT_CONFIG,10 CertTypes,11 HTTPVersionConfig,2 unmodified lines14 TimeoutConfig,15 TimeoutTypes,16 VerifyTypes,17 )16-from ..interfaces import AsyncDispatcher, ConcurrencyBackend18 from ..models import AsyncRequest, AsyncResponse, Origin19 from .http2 import HTTP2Connection20 from .http11 import HTTP11Connection21 106 unmodified linesmodified:httpx/dispatch/http11.py+1 added-2 removed
1 import typing2 3 import h114 5-from ..concurrency.asyncio import TimeoutFlag5+from ..concurrency.base import BaseReader, BaseWriter, ConcurrencyBackend, TimeoutFlag6 from ..config import TimeoutConfig, TimeoutTypes7-from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend7 from ..models import AsyncRequest, AsyncResponse8 9 H11Event = typing.Union[10 h11.Request,177 unmodified linesmodified:httpx/dispatch/http2.py+1 added-2 removed
2 unmodified lines3 4 import h2.connection5 import h2.events6 7-from ..concurrency.asyncio import TimeoutFlag7+from ..concurrency.base import BaseReader, BaseWriter, ConcurrencyBackend, TimeoutFlag8 from ..config import TimeoutConfig, TimeoutTypes9-from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend9 from ..models import AsyncRequest, AsyncResponse10 11 12 class HTTP2Connection:164 unmodified linesmodified:httpx/dispatch/threaded.py+2 added-1 removed
1+from .base import AsyncDispatcher, Dispatcher2+from ..concurrency.base import ConcurrencyBackend3 from ..config import CertTypes, TimeoutTypes, VerifyTypes2-from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher4 from ..models import (5 AsyncRequest,6 AsyncRequestData,7 AsyncResponse,90 unmodified linesmodified:httpx/dispatch/wsgi.py+1 added-1 removed
1 import io2 import typing3 4+from .base import Dispatcher5 from ..config import CertTypes, TimeoutTypes, VerifyTypes5-from ..interfaces import Dispatcher6 from ..models import Request, Response7 8 9 class WSGIDispatch(Dispatcher):155 unmodified linesmodified:httpx/__init__.py+8 added-9 removed
1 from .__version__ import __description__, __title__, __version__2 from .api import delete, get, head, options, patch, post, put, request3 from .client import AsyncClient, Client4 from .concurrency.asyncio import AsyncioBackend5+from .concurrency.base import (6+ BaseBackgroundManager,7+ BasePoolSemaphore,8+ BaseReader,9+ BaseWriter,10+ ConcurrencyBackend,11+)12 from .config import (13 USER_AGENT,14 CertTypes,15 HTTPVersionConfig,3 unmodified lines19 TimeoutConfig,20 TimeoutTypes,21 VerifyTypes,22 )23+from .dispatch.base import AsyncDispatcher, Dispatcher24 from .dispatch.connection import HTTPConnection25 from .dispatch.connection_pool import ConnectionPool26 from .exceptions import (27 ConnectTimeout,11 unmodified lines39 Timeout,40 TooManyRedirects,41 WriteTimeout,42 )35-from .interfaces import (36- AsyncDispatcher,37- BaseBackgroundManager,38- BasePoolSemaphore,39- BaseReader,40- BaseWriter,41- ConcurrencyBackend,42- Dispatcher,43-)43 from .models import (44 URL,45 AsyncRequest,46 AsyncRequestData,90 unmodified linesmodified:httpx/client.py+2 added-1 removed
4 unmodified lines5 import hstspreload6 7 from .auth import HTTPBasicAuth8 from .concurrency.asyncio import AsyncioBackend9+from .concurrency.base import ConcurrencyBackend10 from .config import (11 DEFAULT_MAX_REDIRECTS,12 DEFAULT_POOL_LIMITS,13 DEFAULT_TIMEOUT_CONFIG,3 unmodified lines17 TimeoutTypes,18 VerifyTypes,19 )20 from .dispatch.asgi import ASGIDispatch21+from .dispatch.base import AsyncDispatcher, Dispatcher22 from .dispatch.connection_pool import ConnectionPool23 from .dispatch.threaded import ThreadedDispatcher24 from .dispatch.wsgi import WSGIDispatch25 from .exceptions import (2 unmodified lines28 RedirectBodyUnavailable,29 RedirectLoop,30 TooManyRedirects,31 )30-from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher32 from .models import (33 URL,34 AsyncRequest,35 AsyncRequestData,952 unmodified linesdeleted:httpx/interfaces.py-239 removed
1-import ssl2-import typing3-from types import TracebackType4-5-from .config import CertTypes, PoolLimits, TimeoutConfig, TimeoutTypes, VerifyTypes6-from .models import (7- AsyncRequest,8- AsyncRequestData,9- AsyncResponse,10- HeaderTypes,11- QueryParamTypes,12- Request,13- RequestData,14- Response,15- URLTypes,16-)17-18-19-class AsyncDispatcher:20- """21- Base class for async dispatcher classes, that handle sending the request.22-23- Stubs out the interface, as well as providing a `.request()` convenience24- implementation, to make it easy to use or test stand-alone dispatchers,25- without requiring a complete `Client` instance.26- """27-28- async def request(29- self,30- method: str,31- url: URLTypes,32- *,33- data: AsyncRequestData = b"",34- params: QueryParamTypes = None,35- headers: HeaderTypes = None,36- verify: VerifyTypes = None,37- cert: CertTypes = None,38- timeout: TimeoutTypes = None,39- ) -> AsyncResponse:40- request = AsyncRequest(method, url, data=data, params=params, headers=headers)41- return await self.send(request, verify=verify, cert=cert, timeout=timeout)42-43- async def send(44- self,45- request: AsyncRequest,46- verify: VerifyTypes = None,47- cert: CertTypes = None,48- timeout: TimeoutTypes = None,49- ) -> AsyncResponse:50- raise NotImplementedError() # pragma: nocover51-52- async def close(self) -> None:53- pass # pragma: nocover54-55- async def __aenter__(self) -> "AsyncDispatcher":56- return self57-58- async def __aexit__(59- self,60- exc_type: typing.Type[BaseException] = None,61- exc_value: BaseException = None,62- traceback: TracebackType = None,63- ) -> None:64- await self.close()65-66-67-class Dispatcher:68- """69- Base class for synchronous dispatcher classes, that handle sending the request.70-71- Stubs out the interface, as well as providing a `.request()` convenience72- implementation, to make it easy to use or test stand-alone dispatchers,73- without requiring a complete `Client` instance.74- """75-76- def request(77- self,78- method: str,79- url: URLTypes,80- *,81- data: RequestData = b"",82- params: QueryParamTypes = None,83- headers: HeaderTypes = None,84- verify: VerifyTypes = None,85- cert: CertTypes = None,86- timeout: TimeoutTypes = None,87- ) -> Response:88- request = Request(method, url, data=data, params=params, headers=headers)89- return self.send(request, verify=verify, cert=cert, timeout=timeout)90-91- def send(92- self,93- request: Request,94- verify: VerifyTypes = None,95- cert: CertTypes = None,96- timeout: TimeoutTypes = None,97- ) -> Response:98- raise NotImplementedError() # pragma: nocover99-100- def close(self) -> None:101- pass # pragma: nocover102-103- def __enter__(self) -> "Dispatcher":104- return self105-106- def __exit__(107- self,108- exc_type: typing.Type[BaseException] = None,109- exc_value: BaseException = None,110- traceback: TracebackType = None,111- ) -> None:112- self.close()113-114-115-class BaseReader:116- """117- A stream reader. Abstracts away any asyncio-specific interfaces118- into a more generic base class, that we can use with alternate119- backend, or for stand-alone test cases.120- """121-122- async def read(123- self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None124- ) -> bytes:125- raise NotImplementedError() # pragma: no cover126-127- def is_connection_dropped(self) -> bool:128- raise NotImplementedError() # pragma: no cover129-130-131-class BaseWriter:132- """133- A stream writer. Abstracts away any asyncio-specific interfaces134- into a more generic base class, that we can use with alternate135- backend, or for stand-alone test cases.136- """137-138- def write_no_block(self, data: bytes) -> None:139- raise NotImplementedError() # pragma: no cover140-141- async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:142- raise NotImplementedError() # pragma: no cover143-144- async def close(self) -> None:145- raise NotImplementedError() # pragma: no cover146-147-148-class BaseQueue:149- """150- A FIFO queue. Abstracts away any asyncio-specific interfaces.151- """152-153- async def get(self) -> typing.Any:154- raise NotImplementedError() # pragma: no cover155-156- async def put(self, value: typing.Any) -> None:157- raise NotImplementedError() # pragma: no cover158-159-160-class BasePoolSemaphore:161- """162- A semaphore for use with connection pooling.163-164- Abstracts away any asyncio-specific interfaces.165- """166-167- async def acquire(self) -> None:168- raise NotImplementedError() # pragma: no cover169-170- def release(self) -> None:171- raise NotImplementedError() # pragma: no cover172-173-174-class ConcurrencyBackend:175- async def connect(176- self,177- hostname: str,178- port: int,179- ssl_context: typing.Optional[ssl.SSLContext],180- timeout: TimeoutConfig,181- ) -> typing.Tuple[BaseReader, BaseWriter, str]:182- raise NotImplementedError() # pragma: no cover183-184- def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:185- raise NotImplementedError() # pragma: no cover186-187- async def run_in_threadpool(188- self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any189- ) -> typing.Any:190- raise NotImplementedError() # pragma: no cover191-192- async def iterate_in_threadpool(self, iterator): # type: ignore193- class IterationComplete(Exception):194- pass195-196- def next_wrapper(iterator): # type: ignore197- try:198- return next(iterator)199- except StopIteration:200- raise IterationComplete()201-202- while True:203- try:204- yield await self.run_in_threadpool(next_wrapper, iterator)205- except IterationComplete:206- break207-208- def run(209- self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any210- ) -> typing.Any:211- raise NotImplementedError() # pragma: no cover212-213- def iterate(self, async_iterator): # type: ignore214- while True:215- try:216- yield self.run(async_iterator.__anext__)217- except StopAsyncIteration:218- break219-220- def create_queue(self, max_size: int) -> BaseQueue:221- raise NotImplementedError() # pragma: no cover222-223- def background_manager(224- self, coroutine: typing.Callable, args: typing.Any225- ) -> "BaseBackgroundManager":226- raise NotImplementedError() # pragma: no cover227-228-229-class BaseBackgroundManager:230- async def __aenter__(self) -> "BaseBackgroundManager":231- raise NotImplementedError() # pragma: no cover232-233- async def __aexit__(234- self,235- exc_type: typing.Type[BaseException] = None,236- exc_value: BaseException = None,237- traceback: TracebackType = None,238- ) -> None:239- raise NotImplementedError() # pragma: no cover