threaded.py
This file
Path
http3/dispatch/threaded.py
96 lines · 3.0 KiB · Python
Last changed by
Int status codes (#92)Tom Christiebefore adoption56a7943
History of this fileTake it
http3 (#86)Tom Christiebefore adoptionc9747aa
lines 1–96why, one step back1from ..config import CertTypes, TimeoutTypes, VerifyTypes2from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher3from ..models import (4 AsyncRequest,5 AsyncRequestData,6 AsyncResponse,7 AsyncResponseContent,8 Request,9 RequestData,10 Response,11 ResponseContent,12)131415class ThreadedDispatcher(AsyncDispatcher):16 """17 The ThreadedDispatcher class is used to mediate between the Client18 (which always uses async under the hood), and a synchronous `Dispatch`19 class.20 """2122 def __init__(self, dispatch: Dispatcher, backend: ConcurrencyBackend) -> None:23 self.sync_dispatcher = dispatch24 self.backend = backend2526 async def send(27 self,28 request: AsyncRequest,29 verify: VerifyTypes = None,30 cert: CertTypes = None,31 timeout: TimeoutTypes = None,32 ) -> AsyncResponse:33 concurrency_backend = self.backend3435 data = getattr(request, "content", getattr(request, "content_aiter", None))36 sync_data = self._sync_request_data(data)3738 sync_request = Request(39 method=request.method,40 url=request.url,41 headers=request.headers,42 data=sync_data,43 )4445 func = self.sync_dispatcher.send46 kwargs = {47 "request": sync_request,48 "verify": verify,49 "cert": cert,50 "timeout": timeout,51 }52 sync_response = await self.backend.run_in_threadpool(func, **kwargs)53 assert isinstance(sync_response, Response)5455 content = getattr(56 sync_response, "_raw_content", getattr(sync_response, "_raw_stream", None)57 )5859 async_content = self._async_response_content(content)6061 async def async_on_close() -> None:62 nonlocal concurrency_backend, sync_response63 await concurrency_backend.run_in_threadpool(sync_response.close)6465 return AsyncResponse(66 status_code=sync_response.status_code,67 protocol=sync_response.protocol,68 headers=sync_response.headers,69 content=async_content,70 on_close=async_on_close,71 request=request,72 history=sync_response.history,73 )7475 async def close(self) -> None:76 """77 The `.close()` method runs the `Dispatcher.close()` within a threadpool,78 so as not to block the async event loop.79 """80 func = self.sync_dispatcher.close81 await self.backend.run_in_threadpool(func)8283 def _async_response_content(self, content: ResponseContent) -> AsyncResponseContent:84 if isinstance(content, bytes):85 return content8687 # Coerce an async iterator into an iterator, with each item in the88 # iteration run within the event loop.89 assert hasattr(content, "__iter__")90 return self.backend.iterate_in_threadpool(content)9192 def _sync_request_data(self, data: AsyncRequestData) -> RequestData:93 if isinstance(data, bytes):94 return data9596 return self.backend.iterate(data)