Skip to content
Myr

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

13 files+300 added−293 removed

modified:httpx/concurrency/asyncio.py+4 added-35 removed
12 unmodified lines
13import ssl14import typing15from types import TracebackType1617from ..config import PoolLimits, TimeoutConfig18from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19from ..interfaces import (17from .base import (18 BaseBackgroundManager,19 BasePoolSemaphore,20 BaseQueue,21 BaseReader,22 BaseWriter,23 ConcurrencyBackend,24 TimeoutFlag,25)26from ..config import PoolLimits, TimeoutConfig27from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout2829SSL_MONKEY_PATCH_APPLIED = False3031
17 unmodified lines
4950 MonkeyPatch.write = _fixed_write515252class TimeoutFlag:53 """54 A timeout flag holds a state of either read-timeout or write-timeout mode.5556 We use this so that we can attempt both reads and writes concurrently, while57 only enforcing timeouts in one direction.5859 During a request/response cycle we start in write-timeout mode.6061 Once we've sent a request fully, or once we start seeing a response,62 then we switch to read-timeout mode instead.63 """6465 def __init__(self) -> None:66 self.raise_on_read_timeout = False67 self.raise_on_write_timeout = True6869 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 = False7576 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 = True828353class Reader(BaseReader):54 def __init__(55 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig56 ) -> None:
190 unmodified lines
added:httpx/concurrency/base.py+164 added
1import ssl2import typing3from types import TracebackType45from ..config import PoolLimits, TimeoutConfig678class TimeoutFlag:9 """10 A timeout flag holds a state of either read-timeout or write-timeout mode.1112 We use this so that we can attempt both reads and writes concurrently, while13 only enforcing timeouts in one direction.1415 During a request/response cycle we start in write-timeout mode.1617 Once we've sent a request fully, or once we start seeing a response,18 then we switch to read-timeout mode instead.19 """2021 def __init__(self) -> None:22 self.raise_on_read_timeout = False23 self.raise_on_write_timeout = True2425 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 = False3132 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 = True383940class 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 """4647 async def read(48 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None49 ) -> bytes:50 raise NotImplementedError() # pragma: no cover5152 def is_connection_dropped(self) -> bool:53 raise NotImplementedError() # pragma: no cover545556class 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 """6263 def write_no_block(self, data: bytes) -> None:64 raise NotImplementedError() # pragma: no cover6566 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:67 raise NotImplementedError() # pragma: no cover6869 async def close(self) -> None:70 raise NotImplementedError() # pragma: no cover717273class BaseQueue:74 """75 A FIFO queue. Abstracts away any asyncio-specific interfaces.76 """7778 async def get(self) -> typing.Any:79 raise NotImplementedError() # pragma: no cover8081 async def put(self, value: typing.Any) -> None:82 raise NotImplementedError() # pragma: no cover838485class BasePoolSemaphore:86 """87 A semaphore for use with connection pooling.8889 Abstracts away any asyncio-specific interfaces.90 """9192 async def acquire(self) -> None:93 raise NotImplementedError() # pragma: no cover9495 def release(self) -> None:96 raise NotImplementedError() # pragma: no cover979899class 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 cover108109 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:110 raise NotImplementedError() # pragma: no cover111112 async def run_in_threadpool(113 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any114 ) -> typing.Any:115 raise NotImplementedError() # pragma: no cover116117 async def iterate_in_threadpool(self, iterator): # type: ignore118 class IterationComplete(Exception):119 pass120121 def next_wrapper(iterator): # type: ignore122 try:123 return next(iterator)124 except StopIteration:125 raise IterationComplete()126127 while True:128 try:129 yield await self.run_in_threadpool(next_wrapper, iterator)130 except IterationComplete:131 break132133 def run(134 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any135 ) -> typing.Any:136 raise NotImplementedError() # pragma: no cover137138 def iterate(self, async_iterator): # type: ignore139 while True:140 try:141 yield self.run(async_iterator.__anext__)142 except StopAsyncIteration:143 break144145 def create_queue(self, max_size: int) -> BaseQueue:146 raise NotImplementedError() # pragma: no cover147148 def background_manager(149 self, coroutine: typing.Callable, args: typing.Any150 ) -> "BaseBackgroundManager":151 raise NotImplementedError() # pragma: no cover152153154class BaseBackgroundManager:155 async def __aenter__(self) -> "BaseBackgroundManager":156 raise NotImplementedError() # pragma: no cover157158 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 cover
modified:httpx/dispatch/asgi.py+2 added-1 removed
1import asyncio2import typing34from .base import AsyncDispatcher5from ..concurrency.base import ConcurrencyBackend6from ..concurrency.asyncio import AsyncioBackend7from ..config import CertTypes, TimeoutTypes, VerifyTypes6from ..interfaces import AsyncDispatcher, ConcurrencyBackend8from ..models import AsyncRequest, AsyncResponse91011class ASGIDispatch(AsyncDispatcher):
185 unmodified lines
added:httpx/dispatch/base.py+111 added
1import typing2from types import TracebackType34from ..config import CertTypes, TimeoutTypes, VerifyTypes5from ..models import (6 AsyncRequest,7 AsyncRequestData,8 AsyncResponse,9 HeaderTypes,10 QueryParamTypes,11 Request,12 RequestData,13 Response,14 URLTypes,15)161718class AsyncDispatcher:19 """20 Base class for async dispatcher classes, that handle sending the request.2122 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 """2627 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)4142 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: nocover5051 async def close(self) -> None:52 pass # pragma: nocover5354 async def __aenter__(self) -> "AsyncDispatcher":55 return self5657 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()646566class Dispatcher:67 """68 Base class for synchronous dispatcher classes, that handle sending the request.6970 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 """7475 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)8990 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: nocover9899 def close(self) -> None:100 pass # pragma: nocover101102 def __enter__(self) -> "Dispatcher":103 return self104105 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
1import typing23from .base import AsyncDispatcher4from ..concurrency.asyncio import AsyncioBackend5from ..concurrency.base import ConcurrencyBackend6from ..config import (7 DEFAULT_POOL_LIMITS,8 DEFAULT_TIMEOUT_CONFIG,9 CertTypes,
1 unmodified line
11 PoolLimits,12 TimeoutTypes,13 VerifyTypes,14)13from ..interfaces import AsyncDispatcher, ConcurrencyBackend15from ..models import AsyncRequest, AsyncResponse, Origin16from .connection import HTTPConnection1718CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]
151 unmodified lines
modified:httpx/dispatch/connection.py+2 added-1 removed
1import functools2import ssl3import typing45from .base import AsyncDispatcher6from ..concurrency.asyncio import AsyncioBackend7from ..concurrency.base import ConcurrencyBackend8from ..config import (9 DEFAULT_TIMEOUT_CONFIG,10 CertTypes,11 HTTPVersionConfig,
2 unmodified lines
14 TimeoutConfig,15 TimeoutTypes,16 VerifyTypes,17)16from ..interfaces import AsyncDispatcher, ConcurrencyBackend18from ..models import AsyncRequest, AsyncResponse, Origin19from .http2 import HTTP2Connection20from .http11 import HTTP11Connection21
106 unmodified lines
modified:httpx/dispatch/http11.py+1 added-2 removed
1import typing23import h1145from ..concurrency.asyncio import TimeoutFlag5from ..concurrency.base import BaseReader, BaseWriter, ConcurrencyBackend, TimeoutFlag6from ..config import TimeoutConfig, TimeoutTypes7from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend7from ..models import AsyncRequest, AsyncResponse89H11Event = typing.Union[10 h11.Request,
177 unmodified lines
modified:httpx/dispatch/http2.py+1 added-2 removed
2 unmodified lines
34import h2.connection5import h2.events67from ..concurrency.asyncio import TimeoutFlag7from ..concurrency.base import BaseReader, BaseWriter, ConcurrencyBackend, TimeoutFlag8from ..config import TimeoutConfig, TimeoutTypes9from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend9from ..models import AsyncRequest, AsyncResponse101112class HTTP2Connection:
164 unmodified lines
modified:httpx/dispatch/threaded.py+2 added-1 removed
1from .base import AsyncDispatcher, Dispatcher2from ..concurrency.base import ConcurrencyBackend3from ..config import CertTypes, TimeoutTypes, VerifyTypes2from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher4from ..models import (5 AsyncRequest,6 AsyncRequestData,7 AsyncResponse,
90 unmodified lines
modified:httpx/dispatch/wsgi.py+1 added-1 removed
1import io2import typing34from .base import Dispatcher5from ..config import CertTypes, TimeoutTypes, VerifyTypes5from ..interfaces import Dispatcher6from ..models import Request, Response789class WSGIDispatch(Dispatcher):
155 unmodified lines
modified:httpx/__init__.py+8 added-9 removed
1from .__version__ import __description__, __title__, __version__2from .api import delete, get, head, options, patch, post, put, request3from .client import AsyncClient, Client4from .concurrency.asyncio import AsyncioBackend5from .concurrency.base import (6 BaseBackgroundManager,7 BasePoolSemaphore,8 BaseReader,9 BaseWriter,10 ConcurrencyBackend,11)12from .config import (13 USER_AGENT,14 CertTypes,15 HTTPVersionConfig,
3 unmodified lines
19 TimeoutConfig,20 TimeoutTypes,21 VerifyTypes,22)23from .dispatch.base import AsyncDispatcher, Dispatcher24from .dispatch.connection import HTTPConnection25from .dispatch.connection_pool import ConnectionPool26from .exceptions import (27 ConnectTimeout,
11 unmodified lines
39 Timeout,40 TooManyRedirects,41 WriteTimeout,42)35from .interfaces import (36 AsyncDispatcher,37 BaseBackgroundManager,38 BasePoolSemaphore,39 BaseReader,40 BaseWriter,41 ConcurrencyBackend,42 Dispatcher,43)43from .models import (44 URL,45 AsyncRequest,46 AsyncRequestData,
90 unmodified lines
modified:httpx/client.py+2 added-1 removed
4 unmodified lines
5import hstspreload67from .auth import HTTPBasicAuth8from .concurrency.asyncio import AsyncioBackend9from .concurrency.base import ConcurrencyBackend10from .config import (11 DEFAULT_MAX_REDIRECTS,12 DEFAULT_POOL_LIMITS,13 DEFAULT_TIMEOUT_CONFIG,
3 unmodified lines
17 TimeoutTypes,18 VerifyTypes,19)20from .dispatch.asgi import ASGIDispatch21from .dispatch.base import AsyncDispatcher, Dispatcher22from .dispatch.connection_pool import ConnectionPool23from .dispatch.threaded import ThreadedDispatcher24from .dispatch.wsgi import WSGIDispatch25from .exceptions import (
2 unmodified lines
28 RedirectBodyUnavailable,29 RedirectLoop,30 TooManyRedirects,31)30from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher32from .models import (33 URL,34 AsyncRequest,35 AsyncRequestData,
952 unmodified lines
deleted:httpx/interfaces.py-239 removed
1import ssl2import typing3from types import TracebackType45from .config import CertTypes, PoolLimits, TimeoutConfig, TimeoutTypes, VerifyTypes6from .models import (7 AsyncRequest,8 AsyncRequestData,9 AsyncResponse,10 HeaderTypes,11 QueryParamTypes,12 Request,13 RequestData,14 Response,15 URLTypes,16)171819class AsyncDispatcher:20 """21 Base class for async dispatcher classes, that handle sending the request.2223 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 """2728 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)4243 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: nocover5152 async def close(self) -> None:53 pass # pragma: nocover5455 async def __aenter__(self) -> "AsyncDispatcher":56 return self5758 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()656667class Dispatcher:68 """69 Base class for synchronous dispatcher classes, that handle sending the request.7071 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 """7576 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)9091 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: nocover99100 def close(self) -> None:101 pass # pragma: nocover102103 def __enter__(self) -> "Dispatcher":104 return self105106 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()113114115class 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 """121122 async def read(123 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None124 ) -> bytes:125 raise NotImplementedError() # pragma: no cover126127 def is_connection_dropped(self) -> bool:128 raise NotImplementedError() # pragma: no cover129130131class 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 """137138 def write_no_block(self, data: bytes) -> None:139 raise NotImplementedError() # pragma: no cover140141 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:142 raise NotImplementedError() # pragma: no cover143144 async def close(self) -> None:145 raise NotImplementedError() # pragma: no cover146147148class BaseQueue:149 """150 A FIFO queue. Abstracts away any asyncio-specific interfaces.151 """152153 async def get(self) -> typing.Any:154 raise NotImplementedError() # pragma: no cover155156 async def put(self, value: typing.Any) -> None:157 raise NotImplementedError() # pragma: no cover158159160class BasePoolSemaphore:161 """162 A semaphore for use with connection pooling.163164 Abstracts away any asyncio-specific interfaces.165 """166167 async def acquire(self) -> None:168 raise NotImplementedError() # pragma: no cover169170 def release(self) -> None:171 raise NotImplementedError() # pragma: no cover172173174class 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 cover183184 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:185 raise NotImplementedError() # pragma: no cover186187 async def run_in_threadpool(188 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any189 ) -> typing.Any:190 raise NotImplementedError() # pragma: no cover191192 async def iterate_in_threadpool(self, iterator): # type: ignore193 class IterationComplete(Exception):194 pass195196 def next_wrapper(iterator): # type: ignore197 try:198 return next(iterator)199 except StopIteration:200 raise IterationComplete()201202 while True:203 try:204 yield await self.run_in_threadpool(next_wrapper, iterator)205 except IterationComplete:206 break207208 def run(209 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any210 ) -> typing.Any:211 raise NotImplementedError() # pragma: no cover212213 def iterate(self, async_iterator): # type: ignore214 while True:215 try:216 yield self.run(async_iterator.__anext__)217 except StopAsyncIteration:218 break219220 def create_queue(self, max_size: int) -> BaseQueue:221 raise NotImplementedError() # pragma: no cover222223 def background_manager(224 self, coroutine: typing.Callable, args: typing.Any225 ) -> "BaseBackgroundManager":226 raise NotImplementedError() # pragma: no cover227228229class BaseBackgroundManager:230 async def __aenter__(self) -> "BaseBackgroundManager":231 raise NotImplementedError() # pragma: no cover232233 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