threaded.py
This file
Path
httpcore/dispatch/threaded.py
97 lines · 3.1 KiB · Python
Last changed by
Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
History of this fileTake it
Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 1–97why, 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 reason_phrase=sync_response.reason_phrase,68 protocol=sync_response.protocol,69 headers=sync_response.headers,70 content=async_content,71 on_close=async_on_close,72 request=request,73 history=sync_response.history,74 )7576 async def close(self) -> None:77 """78 The `.close()` method runs the `Dispatcher.close()` within a threadpool,79 so as not to block the async event loop.80 """81 func = self.sync_dispatcher.close82 await self.backend.run_in_threadpool(func)8384 def _async_response_content(self, content: ResponseContent) -> AsyncResponseContent:85 if isinstance(content, bytes):86 return content8788 # Coerce an async iterator into an iterator, with each item in the89 # iteration run within the event loop.90 assert hasattr(content, "__iter__")91 return self.backend.iterate_in_threadpool(content)9293 def _sync_request_data(self, data: AsyncRequestData) -> RequestData:94 if isinstance(data, bytes):95 return data9697 return self.backend.iterate(data)