Drop 'Response(on_close=...)' from API (#1572)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by GitHub · parent 4870cb5 · Browse files · 5 files·+113 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+113 added−21 removed
- tests:+43 added−1 removed
- other:+70 added−20 removed
Provenance
- Commit
073a328- Tree
f120917- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
4870cb5
5 files changed+113 added−21 removed
modified:httpx/_client.py+60 added-12 removed
84 unmodified lines85 # been called explicitly.86 CLOSED = 387 88 89+class BoundSyncStream(SyncByteStream):90+ """91+ A byte stream that is bound to a given response instance, and that92+ ensures the `response.elapsed` is set once the response is closed.93+ """94+95+ def __init__(96+ self, stream: SyncByteStream, response: Response, timer: Timer97+ ) -> None:98+ self._stream = stream99+ self._response = response100+ self._timer = timer101+102+ def __iter__(self) -> typing.Iterator[bytes]:103+ for chunk in self._stream:104+ yield chunk105+106+ def close(self) -> None:107+ seconds = self._timer.sync_elapsed()108+ self._response.elapsed = datetime.timedelta(seconds=seconds)109+ self._stream.close()110+111+112+class BoundAsyncStream(AsyncByteStream):113+ """114+ An async byte stream that is bound to a given response instance, and that115+ ensures the `response.elapsed` is set once the response is closed.116+ """117+118+ def __init__(119+ self, stream: AsyncByteStream, response: Response, timer: Timer120+ ) -> None:121+ self._stream = stream122+ self._response = response123+ self._timer = timer124+125+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:126+ async for chunk in self._stream:127+ yield chunk128+129+ async def aclose(self) -> None:130+ seconds = await self._timer.async_elapsed()131+ self._response.elapsed = datetime.timedelta(seconds=seconds)132+ await self._stream.aclose()133+134+135 class BaseClient:136 def __init__(137 self,138 *,780 unmodified lines919 transport = self._transport_for_url(request.url)920 timer = Timer()921 timer.sync_start()922 923+ if not isinstance(request.stream, SyncByteStream):924+ raise RuntimeError(925+ "Attempted to send an async request with a sync Client instance."926+ )927+928 with request_context(request=request):929 (status_code, headers, stream, extensions) = transport.handle_request(930 request.method.encode(),931 request.url.raw,932 headers=request.headers.raw,882- stream=request.stream, # type: ignore933+ stream=request.stream,934 extensions={"timeout": timeout.as_dict()},935 )936 886- def on_close(response: Response) -> None:887- response.elapsed = datetime.timedelta(seconds=timer.sync_elapsed())888- stream.close()889-937 response = Response(938 status_code,939 headers=headers,940 stream=stream,941 extensions=extensions,942 request=request,896- on_close=on_close,943 )944 945+ response.stream = BoundSyncStream(stream, response=response, timer=timer)946 self.cookies.extract_cookies(response)947 948 status = f"{response.status_code} {response.reason_phrase}"949 response_line = f"{response.http_version} {status}"608 unmodified lines1558 transport = self._transport_for_url(request.url)1559 timer = Timer()1560 await timer.async_start()1561 1562+ if not isinstance(request.stream, AsyncByteStream):1563+ raise RuntimeError(1564+ "Attempted to send an sync request with an AsyncClient instance."1565+ )1566+1567 with request_context(request=request):1568 (1569 status_code,1570 headers,2 unmodified lines1573 ) = await transport.handle_async_request(1574 request.method.encode(),1575 request.url.raw,1576 headers=request.headers.raw,1525- stream=request.stream, # type: ignore1577+ stream=request.stream,1578 extensions={"timeout": timeout.as_dict()},1579 )1580 1529- async def on_close(response: Response) -> None:1530- response.elapsed = datetime.timedelta(seconds=await timer.async_elapsed())1531- await stream.aclose()1532-1581 response = Response(1582 status_code,1583 headers=headers,1584 stream=stream,1585 extensions=extensions,1586 request=request,1539- on_close=on_close,1587 )1588 1589+ response.stream = BoundAsyncStream(stream, response=response, timer=timer)1590 self.cookies.extract_cookies(response)1591 1592 status = f"{response.status_code} {response.reason_phrase}"1593 response_line = f"{response.http_version} {status}"339 unmodified linesmodified:httpx/_models.py+10 added-8 removed
906 unmodified lines907 stream: typing.Union[SyncByteStream, AsyncByteStream] = None,908 request: Request = None,909 extensions: dict = None,910 history: typing.List["Response"] = None,911- on_close: typing.Callable = None,911 ):912 self.status_code = status_code913 self.headers = Headers(headers)914 6 unmodified lines921 self.call_next: typing.Optional[typing.Callable] = None922 923 self.extensions = {} if extensions is None else extensions924 self.history = [] if history is None else list(history)926- self._on_close = on_close925 926 self.is_closed = False927 self.is_stream_consumed = False928 313 unmodified lines1242 """1243 Close the response and release the connection.1244 Automatically called if the response body is read to completion.1245 """1246+ if not isinstance(self.stream, SyncByteStream):1247+ raise RuntimeError("Attempted to call an sync close on an async stream.")1248+1249 if not self.is_closed:1250 self.is_closed = True1250- if self._on_close is not None:1251- with request_context(request=self._request):1252- self._on_close(self)1251+ with request_context(request=self._request):1252+ self.stream.close()1253 1254 async def aread(self) -> bytes:1255 """1256 Read and return the response content.83 unmodified lines1340 """1341 Close the response and release the connection.1342 Automatically called if the response body is read to completion.1343 """1344+ if not isinstance(self.stream, AsyncByteStream):1345+ raise RuntimeError("Attempted to call an async close on an sync stream.")1346+1347 if not self.is_closed:1348 self.is_closed = True1346- if self._on_close is not None:1347- with request_context(request=self._request):1348- await self._on_close(self)1349+ with request_context(request=self._request):1350+ await self.stream.aclose()1351 1352 1353 class Cookies(MutableMapping):1354 """187 unmodified linesmodified:tests/client/test_async_client.py+12 added-1 removed
92 unmodified lines93 yield b"Hello, "94 yield b"world!"95 96 async with httpx.AsyncClient() as client:97- response = await client.request("POST", server.url, content=hello_world())97+ response = await client.post(server.url, content=hello_world())98 assert response.status_code == 20099 100 101 @pytest.mark.usefixtures("async_environment")102+async def test_cannot_stream_sync_request(server):103+ def hello_world(): # pragma: nocover104+ yield b"Hello, "105+ yield b"world!"106+107+ async with httpx.AsyncClient() as client:108+ with pytest.raises(RuntimeError):109+ await client.post(server.url, content=hello_world())110+111+112+@pytest.mark.usefixtures("async_environment")113 async def test_raise_for_status(server):114 async with httpx.AsyncClient() as client:115 for status_code in (200, 400, 404, 500, 505):116 response = await client.request(219 unmodified linesmodified:tests/client/test_client.py+10 added
112 unmodified lines113 assert response.status_code == 200114 assert body == b"Hello, world!"115 116 117+def test_cannot_stream_async_request(server):118+ async def hello_world(): # pragma: nocover119+ yield b"Hello, "120+ yield b"world!"121+122+ with httpx.Client() as client:123+ with pytest.raises(RuntimeError):124+ client.post(server.url, content=hello_world())125+126+127 def test_raise_for_status(server):128 with httpx.Client() as client:129 for status_code in (200, 400, 404, 500, 505):130 response = client.request(273 unmodified linesmodified:tests/models/test_responses.py+21 added
380 unmodified lines381 with pytest.raises(RuntimeError):382 [part for part in response.iter_raw()]383 384 385+def test_close_on_async():386+ response = httpx.Response(387+ 200,388+ content=async_streaming_body(),389+ )390+391+ with pytest.raises(RuntimeError):392+ response.close()393+394+395 def test_iter_raw_increments_updates_counter():396 response = httpx.Response(200, content=streaming_body())397 398 num_downloaded = response.num_bytes_downloaded41 unmodified lines440 [part async for part in response.aiter_raw()]441 442 443 @pytest.mark.asyncio444+async def test_aclose_on_sync():445+ response = httpx.Response(446+ 200,447+ content=streaming_body(),448+ )449+450+ with pytest.raises(RuntimeError):451+ await response.aclose()452+453+454+@pytest.mark.asyncio455 async def test_aiter_raw_increments_updates_counter():456 response = httpx.Response(200, content=async_streaming_body())457 458 num_downloaded = response.num_bytes_downloaded397 unmodified lines