Drop `request.timer` attribute. (#1249)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Drop request.timer attribute * Response(..., elapsed_func=...)
authored by Tom Christie · committed by GitHub · parent 78f2420 · Browse files · 5 files·+43 added−44 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+43 added−44 removed
- tests:+0 added−15 removed
- other:+43 added−29 removed
Provenance
- Commit
a783fe5- Tree
2656108- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
78f2420
5 files changed+43 added−44 removed
modified:httpx/_client.py+7 added
45 unmodified lines46 VerifyTypes,47 )48 from ._utils import (49 NetRCInfo,50+ Timer,51 URLPattern,52 get_environment_proxies,53 get_logger,54 same_origin,756 unmodified lines811 """812 Sends a single request, without handling any redirections.813 """814 transport = self._transport_for_url(request.url)815+ timer = Timer()816+ timer.sync_start()817 818 with map_exceptions(HTTPCORE_EXC_MAP, request=request):819 (820 http_version,13 unmodified lines834 http_version=http_version.decode("ascii"),835 headers=headers,836 stream=stream, # type: ignore837 request=request,838+ elapsed_func=timer.sync_elapsed,839 )840 841 self.cookies.extract_cookies(response)842 594 unmodified lines1437 """1438 Sends a single request, without handling any redirections.1439 """1440 transport = self._transport_for_url(request.url)1441+ timer = Timer()1442+ await timer.async_start()1443 1444 with map_exceptions(HTTPCORE_EXC_MAP, request=request):1445 (1446 http_version,13 unmodified lines1460 http_version=http_version.decode("ascii"),1461 headers=headers,1462 stream=stream, # type: ignore1463 request=request,1464+ elapsed_func=timer.async_elapsed,1465 )1466 1467 self.cookies.extract_cookies(response)1468 314 unmodified linesmodified:httpx/_models.py+7 added-7 removed
45 unmodified lines46 RequestFiles,47 URLTypes,48 )49 from ._utils import (50- ElapsedTimer,50 flatten_queryparams,51 guess_json_utf,52 is_known_encoding,53 normalize_header_key,550 unmodified lines604 self.stream = stream605 else:606 self.stream = encode(data, files, json)607 609- self.timer = ElapsedTimer()608 self.prepare()609 610 def prepare(self) -> None:611 for key, value in self.stream.get_headers().items():63 unmodified lines675 headers: HeaderTypes = None,676 stream: ContentStream = None,677 content: bytes = None,678 history: typing.List["Response"] = None,679+ elapsed_func: typing.Callable = None,680 ):681 self.status_code = status_code682 self.http_version = http_version683 self.headers = Headers(headers)2 unmodified lines686 687 self.call_next: typing.Optional[typing.Callable] = None688 689 self.history = [] if history is None else list(history)690+ self._elapsed_func = elapsed_func691 692 self.is_closed = False693 self.is_stream_consumed = False694 if stream is not None:12 unmodified lines707 raise RuntimeError(708 "'.elapsed' may only be accessed after the response "709 "has been read or closed."710 )711- return self._elapsed711+ return datetime.timedelta(seconds=self._elapsed)712 713 @property714 def request(self) -> Request:715 """259 unmodified lines975 Automatically called if the response body is read to completion.976 """977 if not self.is_closed:978 self.is_closed = True979- if self._request is not None:980- self._elapsed = self.request.timer.elapsed979+ if self._elapsed_func is not None:980+ self._elapsed = self._elapsed_func()981 self._raw_stream.close()982 983 async def aread(self) -> bytes:984 """70 unmodified lines1055 Automatically called if the response body is read to completion.1056 """1057 if not self.is_closed:1058 self.is_closed = True1059- if self._request is not None:1060- self._elapsed = self.request.timer.elapsed1059+ if self._elapsed_func is not None:1060+ self._elapsed = await self._elapsed_func()1061 await self._raw_stream.aclose()1062 1063 1064 class Cookies(MutableMapping):178 unmodified linesmodified:httpx/_utils.py+29 added-22 removed
4 unmodified lines5 import netrc6 import os7 import re8 import sys9+import time10 import typing11 import warnings11-from datetime import timedelta12 from pathlib import Path13-from time import perf_counter14-from types import TracebackType13 from urllib.request import getproxies14 15+import sniffio16+17 from ._types import PrimitiveData18 19 if typing.TYPE_CHECKING: # pragma: no cover20 from ._models import URL370 unmodified lines391 392 return items393 394 395-class ElapsedTimer:396- def __init__(self) -> None:397- self.start: float = perf_counter()398- self.end: typing.Optional[float] = None395+class Timer:396+ async def _get_time(self) -> float:397+ library = sniffio.current_async_library()398+ if library == "trio":399+ import trio400 400- def __enter__(self) -> "ElapsedTimer":401- self.start = perf_counter()402- return self401+ return trio.current_time()402+ elif library == "curio": # pragma: nocover403+ import curio404 404- def __exit__(405- self,406- exc_type: typing.Type[BaseException] = None,407- exc_value: BaseException = None,408- traceback: TracebackType = None,409- ) -> None:410- self.end = perf_counter()405+ return await curio.clock()406 412- @property413- def elapsed(self) -> timedelta:414- if self.end is None:415- return timedelta(seconds=perf_counter() - self.start)416- return timedelta(seconds=self.end - self.start)407+ import asyncio408 409+ return asyncio.get_event_loop().time()410 411+ def sync_start(self) -> None:412+ self.started = time.perf_counter()413+414+ async def async_start(self) -> None:415+ self.started = await self._get_time()416+417+ def sync_elapsed(self) -> float:418+ now = time.perf_counter()419+ return now - self.started420+421+ async def async_elapsed(self) -> float:422+ now = await self._get_time()423+ return now - self.started424+425+426 class URLPattern:427 """428 A utility class currently used for making lookups against proxy keys...429 109 unmodified linesmodified:tests/models/test_responses.py-2 removed
1-import datetime1 import json2 from unittest import mock3 4 import brotli24 unmodified lines29 assert response.reason_phrase == "OK"30 assert response.text == "Hello, world!"31 assert response.request.method == "GET"32 assert response.request.url == "https://example.org"34- assert response.elapsed >= datetime.timedelta(0)33 assert not response.is_error34 35 36 def test_raise_for_status():552 unmodified linesmodified:tests/test_utils.py-13 removed
1-import asyncio1 import os2 import random3 4 import pytest5 6 import httpx7 from httpx._utils import (9- ElapsedTimer,8 NetRCInfo,9 URLPattern,10 get_ca_bundle_from_env,11 get_environment_proxies,162 unmodified lines174 # Two environments is set but both are not correct.175 assert get_ca_bundle_from_env() is None176 177 180-@pytest.mark.asyncio181-async def test_elapsed_timer():182- with ElapsedTimer() as timer:183- assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)184- await asyncio.sleep(0.1)185- await asyncio.sleep(186- 0.1187- ) # test to ensure time spent after timer exits isn't accounted for.188- assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)189-190-178 @pytest.mark.parametrize(179 ["environment", "proxies"],180 [181 ({}, {}),78 unmodified lines