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
Provenance
- Commit
6a1ee0e- Tree
70d8843- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
1f9d015
4 files changed+24 added−11 removed
modified:docs/api.md+1 added-2 removed
54 unmodified lines555657585960596061626396 unmodified lines54 unmodified lines* `.request` - **Request*** `.cookies` - **Cookies*** `.history` - **List[Response]*** `.elapsed` - **[timedelta](https://docs.python.org/3/library/datetime.html)** * The amount of time elapsed between sending the first byte and parsing the headers (not including time spent reading the response). Use * The amount of time elapsed between sending the request and calling `close()` on the corresponding response received for that request. [total_seconds()](https://docs.python.org/3/library/datetime.html#datetime.timedelta.total_seconds) to correctly get the total elapsed seconds.* `def .raise_for_status()` - **None*** `def .json()` - **Any**96 unmodified linesmodified:httpx/client.py+2 added-5 removed
45 unmodified lines46 Response,47 URLTypes,48 )49 from .status_codes import codes50-from .utils import ElapsedTimer, NetRCInfo, get_environment_proxies, get_logger50+from .utils import NetRCInfo, get_environment_proxies, get_logger51 52 logger = get_logger(__name__)53 54 537 unmodified lines592 593 dispatcher = self.dispatcher_for_url(request.url)594 595 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 linesmodified:httpx/models.py+17 added-2 removed
32 unmodified lines33 StreamConsumed,34 )35 from .status_codes import StatusCode36 from .utils import (37+ ElapsedTimer,38 flatten_queryparams,39 guess_json_utf,40 is_known_encoding,41 normalize_header_key,565 unmodified lines607 self.stream = stream608 else:609 self.stream = encode(data, files, json)610 611+ self.timer = ElapsedTimer()612 self.prepare()613 614 def prepare(self) -> None:615 for key, value in self.stream.get_headers().items():46 unmodified lines662 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)670 671 self.request = request671- self.elapsed = datetime.timedelta(0) if elapsed is None else elapsed672 self.call_next: typing.Optional[typing.Callable] = None673 674 self.history = [] if history is None else list(history)675 676 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 = stream685 686 @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._elapsed698+699+ @property700 def reason_phrase(self) -> str:701 return StatusCode.get_reason_phrase(self.status_code)702 703 @property241 unmodified lines945 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()952 953 172 unmodified linesmodified:tests/models/test_responses.py+4 added-2 removed
18 unmodified lines19 yield b"Hello, "20 yield b"world!"21 22 23+@pytest.mark.asyncio23-def test_response():24+async def test_response():25 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)26+27 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_error33 34 35 def test_response_repr():265 unmodified lines