Skip to content
Myr

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

5 files+113 added−21 removed

modified:httpx/_client.py+60 added-12 removed
84 unmodified lines
85 # been called explicitly.86 CLOSED = 3878889class 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 """9495 def __init__(96 self, stream: SyncByteStream, response: Response, timer: Timer97 ) -> None:98 self._stream = stream99 self._response = response100 self._timer = timer101102 def __iter__(self) -> typing.Iterator[bytes]:103 for chunk in self._stream:104 yield chunk105106 def close(self) -> None:107 seconds = self._timer.sync_elapsed()108 self._response.elapsed = datetime.timedelta(seconds=seconds)109 self._stream.close()110111112class 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 """117118 def __init__(119 self, stream: AsyncByteStream, response: Response, timer: Timer120 ) -> None:121 self._stream = stream122 self._response = response123 self._timer = timer124125 async def __aiter__(self) -> typing.AsyncIterator[bytes]:126 async for chunk in self._stream:127 yield chunk128129 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()133134135class BaseClient:136 def __init__(137 self,138 *,
780 unmodified lines
919 transport = self._transport_for_url(request.url)920 timer = Timer()921 timer.sync_start()922923 if not isinstance(request.stream, SyncByteStream):924 raise RuntimeError(925 "Attempted to send an async request with a sync Client instance."926 )927928 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 )936886 def on_close(response: Response) -> None:887 response.elapsed = datetime.timedelta(seconds=timer.sync_elapsed())888 stream.close()889937 response = Response(938 status_code,939 headers=headers,940 stream=stream,941 extensions=extensions,942 request=request,896 on_close=on_close,943 )944945 response.stream = BoundSyncStream(stream, response=response, timer=timer)946 self.cookies.extract_cookies(response)947948 status = f"{response.status_code} {response.reason_phrase}"949 response_line = f"{response.http_version} {status}"
608 unmodified lines
1558 transport = self._transport_for_url(request.url)1559 timer = Timer()1560 await timer.async_start()15611562 if not isinstance(request.stream, AsyncByteStream):1563 raise RuntimeError(1564 "Attempted to send an sync request with an AsyncClient instance."1565 )15661567 with request_context(request=request):1568 (1569 status_code,1570 headers,
2 unmodified lines
1573 ) = 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 )15801529 async def on_close(response: Response) -> None:1530 response.elapsed = datetime.timedelta(seconds=await timer.async_elapsed())1531 await stream.aclose()15321581 response = Response(1582 status_code,1583 headers=headers,1584 stream=stream,1585 extensions=extensions,1586 request=request,1539 on_close=on_close,1587 )15881589 response.stream = BoundAsyncStream(stream, response=response, timer=timer)1590 self.cookies.extract_cookies(response)15911592 status = f"{response.status_code} {response.reason_phrase}"1593 response_line = f"{response.http_version} {status}"
339 unmodified lines
modified:httpx/_models.py+10 added-8 removed
906 unmodified lines
907 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 lines
921 self.call_next: typing.Optional[typing.Callable] = None922923 self.extensions = {} if extensions is None else extensions924 self.history = [] if history is None else list(history)926 self._on_close = on_close925926 self.is_closed = False927 self.is_stream_consumed = False928
313 unmodified lines
1242 """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.")12481249 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()12531254 async def aread(self) -> bytes:1255 """1256 Read and return the response content.
83 unmodified lines
1340 """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.")13461347 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()135113521353class Cookies(MutableMapping):1354 """
187 unmodified lines
modified:tests/client/test_async_client.py+12 added-1 removed
92 unmodified lines
93 yield b"Hello, "94 yield b"world!"9596 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 == 20099100101@pytest.mark.usefixtures("async_environment")102async def test_cannot_stream_sync_request(server):103 def hello_world(): # pragma: nocover104 yield b"Hello, "105 yield b"world!"106107 async with httpx.AsyncClient() as client:108 with pytest.raises(RuntimeError):109 await client.post(server.url, content=hello_world())110111112@pytest.mark.usefixtures("async_environment")113async 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 lines
modified:tests/client/test_client.py+10 added
112 unmodified lines
113 assert response.status_code == 200114 assert body == b"Hello, world!"115116117def test_cannot_stream_async_request(server):118 async def hello_world(): # pragma: nocover119 yield b"Hello, "120 yield b"world!"121122 with httpx.Client() as client:123 with pytest.raises(RuntimeError):124 client.post(server.url, content=hello_world())125126127def 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 lines
modified:tests/models/test_responses.py+21 added
380 unmodified lines
381 with pytest.raises(RuntimeError):382 [part for part in response.iter_raw()]383384385def test_close_on_async():386 response = httpx.Response(387 200,388 content=async_streaming_body(),389 )390391 with pytest.raises(RuntimeError):392 response.close()393394395def test_iter_raw_increments_updates_counter():396 response = httpx.Response(200, content=streaming_body())397398 num_downloaded = response.num_bytes_downloaded
41 unmodified lines
440 [part async for part in response.aiter_raw()]441442443@pytest.mark.asyncio444async def test_aclose_on_sync():445 response = httpx.Response(446 200,447 content=streaming_body(),448 )449450 with pytest.raises(RuntimeError):451 await response.aclose()452453454@pytest.mark.asyncio455async def test_aiter_raw_increments_updates_counter():456 response = httpx.Response(200, content=async_streaming_body())457458 num_downloaded = response.num_bytes_downloaded
397 unmodified lines