Skip to content
Myr

response.elapsed now reflects entire request/response time. (#692)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Changed behaviour of elapsed on response * Fixed api docs for Response elapsed * Minor tweaks to 'request.elapsed' * Response instantiated with content should have elapsed==0 * Fix elapsed time on immediately closed responses.

authored by Tom Christie · committed by GitHub · parent 1f9d015 · Browse files · 4 files+24 added−11 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+24 added−11 removed

  • tests:+4 added−2 removed
  • other:+20 added−9 removed

4 files+24 added−11 removed

modified:docs/api.md+1 added-2 removed
modified:httpx/client.py+2 added-5 removed
45 unmodified lines
46 Response,47 URLTypes,48)49from .status_codes import codes50from .utils import ElapsedTimer, NetRCInfo, get_environment_proxies, get_logger50from .utils import NetRCInfo, get_environment_proxies, get_logger5152logger = get_logger(__name__)5354
537 unmodified lines
592593 dispatcher = self.dispatcher_for_url(request.url)594595 try:596 with ElapsedTimer() as timer:597 response = await dispatcher.send(request, timeout=timeout)596 response = await dispatcher.send(request, timeout=timeout)598 response.elapsed = timer.elapsed599 response.request = request597 except HTTPError as exc:598 # Add the original request to any HTTPError unless599 # there'a already a request attached in the case of600 # a ProxyError.
361 unmodified lines
modified:httpx/models.py+17 added-2 removed
32 unmodified lines
33 StreamConsumed,34)35from .status_codes import StatusCode36from .utils import (37 ElapsedTimer,38 flatten_queryparams,39 guess_json_utf,40 is_known_encoding,41 normalize_header_key,
565 unmodified lines
607 self.stream = stream608 else:609 self.stream = encode(data, files, json)610611 self.timer = ElapsedTimer()612 self.prepare()613614 def prepare(self) -> None:615 for key, value in self.stream.get_headers().items():
46 unmodified lines
662 headers: HeaderTypes = None,663 stream: ContentStream = None,664 content: bytes = None,665 history: typing.List["Response"] = None,664 elapsed: datetime.timedelta = None,666 ):667 self.status_code = status_code668 self.http_version = http_version669 self.headers = Headers(headers)670671 self.request = request671 self.elapsed = datetime.timedelta(0) if elapsed is None else elapsed672 self.call_next: typing.Optional[typing.Callable] = None673674 self.history = [] if history is None else list(history)675676 if stream is None:677 self.is_closed = True678 self.is_stream_consumed = True679 self._raw_content = content or b""680 self._elapsed = request.timer.elapsed681 else:682 self.is_closed = False683 self.is_stream_consumed = False684 self._raw_stream = stream685686 @property687 def elapsed(self) -> datetime.timedelta:688 """689 Returns the time taken for the complete request/response690 cycle to complete.691 """692 if not hasattr(self, "_elapsed"):693 raise RuntimeError(694 "'.elapsed' may only be accessed after the response "695 "has been read or closed."696 )697 return self._elapsed698699 @property700 def reason_phrase(self) -> str:701 return StatusCode.get_reason_phrase(self.status_code)702703 @property
241 unmodified lines
945 Automatically called if the response body is read to completion.946 """947 if not self.is_closed:948 self.is_closed = True949 self._elapsed = self.request.timer.elapsed950 if hasattr(self, "_raw_stream"):951 await self._raw_stream.aclose()952953
172 unmodified lines
modified:tests/models/test_responses.py+4 added-2 removed
18 unmodified lines
19 yield b"Hello, "20 yield b"world!"212223@pytest.mark.asyncio23def test_response():24async def test_response():25 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)2627 assert response.status_code == 20028 assert response.reason_phrase == "OK"29 assert response.text == "Hello, world!"30 assert response.request is REQUEST29 assert response.elapsed == datetime.timedelta(0)31 assert response.elapsed >= datetime.timedelta(0)32 assert not response.is_error333435def test_response_repr():
265 unmodified lines