Skip to content
Myr

TimeoutConfig -> Timeout (#591)

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 d223de8 · Browse files · 17 files+96 added−99 removed
This commit

State

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

Diff stats

17 files+96 added−99 removed

  • tests:+29 added−29 removed
  • other:+67 added−70 removed

17 files+96 added−99 removed

modified:docs/advanced.md+3 added-3 removed
288 unmodified lines
289290Besides, you can pass timeouts in two forms:291292- A number, which sets the read, write and connect timeouts to the same value, as in the examples above.293- A `TimeoutConfig` instance, which allows to define the read, write and connect timeouts independently:293- A `Timeout` instance, which allows to define the read, write and connect timeouts independently:294295```python296timeout = httpx.TimeoutConfig(296timeout = httpx.Timeout(297 connect_timeout=5,298 read_timeout=10,299 write_timeout=15300)
19 unmodified lines
320async with httpx.Client(timeout=None) as client:321 await client.get(url) # Does not timeout, returns after 10s322323324timeout = httpx.TimeoutConfig(324timeout = httpx.Timeout(325 connect_timeout=5,326 read_timeout=None,327 write_timeout=5328)
107 unmodified lines
modified:docs/environment_variables.md+2 added-2 removed
44 unmodified lines
45TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - acquire_connection origin=Origin(scheme='https' host='google.com' port=443)46TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - new_connection connection=HTTPConnection(origin=Origin(scheme='https' host='google.com' port=443))47TRACE [2019-11-06 19:18:56] httpx.config - load_ssl_context verify=True cert=None trust_env=True http_versions=HTTPVersionConfig(['HTTP/1.1', 'HTTP/2'])48TRACE [2019-11-06 19:18:56] httpx.config - load_verify_locations cafile=/Users/florimond/Developer/python-projects/httpx/venv/lib/python3.8/site-packages/certifi/cacert.pem49TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - start_connect host='google.com' port=443 timeout=TimeoutConfig(timeout=5.0)49TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - start_connect host='google.com' port=443 timeout=Timeout(timeout=5.0)50TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - connected http_version='HTTP/2'51TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - send_headers stream_id=1 method='GET' target='/' headers=[(b':method', b'GET'), (b':authority', b'google.com'), (b':scheme', b'https'), (b':path', b'/'), (b'user-agent', b'python-httpx/0.7.6'), (b'accept', b'*/*'), (b'accept-encoding', b'gzip, deflate, br'), (b'connection', b'keep-alive')]52TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - end_stream stream_id=153TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<RemoteSettingsChanged changed_settings:{ChangedSetting(setting=SettingCodes.MAX_CONCURRENT_STREAMS, original_value=None, new_value=100), ChangedSetting(setting=SettingCodes.INITIAL_WINDOW_SIZE, original_value=65535, new_value=1048576), ChangedSetting(setting=SettingCodes.MAX_HEADER_LIST_SIZE, original_value=None, new_value=16384)}>
4 unmodified lines
58TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - acquire_connection origin=Origin(scheme='https' host='www.google.com' port=443)59TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - new_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))60TRACE [2019-11-06 19:18:56] httpx.config - load_ssl_context verify=True cert=None trust_env=True http_versions=HTTPVersionConfig(['HTTP/1.1', 'HTTP/2'])61TRACE [2019-11-06 19:18:56] httpx.config - load_verify_locations cafile=/Users/florimond/Developer/python-projects/httpx/venv/lib/python3.8/site-packages/certifi/cacert.pem62TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - start_connect host='www.google.com' port=443 timeout=TimeoutConfig(timeout=5.0)62TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - start_connect host='www.google.com' port=443 timeout=Timeout(timeout=5.0)63TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - connected http_version='HTTP/2'64TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - send_headers stream_id=1 method='GET' target='/' headers=[(b':method', b'GET'), (b':authority', b'www.google.com'), (b':scheme', b'https'), (b':path', b'/'), (b'user-agent', b'python-httpx/0.7.6'), (b'accept', b'*/*'), (b'accept-encoding', b'gzip, deflate, br'), (b'connection', b'keep-alive')]65TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - end_stream stream_id=166TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<RemoteSettingsChanged changed_settings:{ChangedSetting(setting=SettingCodes.MAX_CONCURRENT_STREAMS, original_value=None, new_value=100), ChangedSetting(setting=SettingCodes.INITIAL_WINDOW_SIZE, original_value=65535, new_value=1048576), ChangedSetting(setting=SettingCodes.MAX_HEADER_LIST_SIZE, original_value=None, new_value=16384)}>
90 unmodified lines
modified:httpx/concurrency/asyncio.py+7 added-7 removed
3 unmodified lines
4import sys5import typing6from types import TracebackType78from ..config import PoolLimits, TimeoutConfig8from ..config import PoolLimits, Timeout9from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout10from .base import (11 BaseBackgroundManager,12 BaseEvent,
31 unmodified lines
44 def __init__(45 self,46 stream_reader: asyncio.StreamReader,47 stream_writer: asyncio.StreamWriter,48 timeout: TimeoutConfig,48 timeout: Timeout,49 ):50 self.stream_reader = stream_reader51 self.stream_writer = stream_writer52 self.timeout = timeout
1 unmodified line
5455 self._inner: typing.Optional[SocketStream] = None5657 async def start_tls(58 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig58 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout59 ) -> "SocketStream":60 loop = asyncio.get_event_loop()6162 stream_reader = asyncio.StreamReader()
69 unmodified lines
132 ident = ssl_object.selected_alpn_protocol()133 return "HTTP/2" if ident == "h2" else "HTTP/1.1"134135 async def read(136 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None136 self, n: int, timeout: Timeout = None, flag: TimeoutFlag = None137 ) -> bytes:138 if timeout is None:139 timeout = self.timeout140
24 unmodified lines
165 def write_no_block(self, data: bytes) -> None:166 self.stream_writer.write(data) # pragma: nocover167168 async def write(169 self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None169 self, data: bytes, timeout: Timeout = None, flag: TimeoutFlag = None170 ) -> None:171 if not data:172 return173
89 unmodified lines
263 self,264 hostname: str,265 port: int,266 ssl_context: typing.Optional[ssl.SSLContext],267 timeout: TimeoutConfig,267 timeout: Timeout,268 ) -> SocketStream:269 try:270 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore271 asyncio.open_connection(hostname, port, ssl=ssl_context),
10 unmodified lines
282 self,283 path: str,284 hostname: typing.Optional[str],285 ssl_context: typing.Optional[ssl.SSLContext],286 timeout: TimeoutConfig,286 timeout: Timeout,287 ) -> SocketStream:288 server_hostname = hostname if ssl_context else None289290 try:
63 unmodified lines
modified:httpx/concurrency/auto.py+3 added-3 removed
1 unmodified line
2import typing34import sniffio56from ..config import PoolLimits, TimeoutConfig6from ..config import PoolLimits, Timeout7from .base import (8 BaseBackgroundManager,9 BaseEvent,10 BasePoolSemaphore,
17 unmodified lines
28 self,29 hostname: str,30 port: int,31 ssl_context: typing.Optional[ssl.SSLContext],32 timeout: TimeoutConfig,32 timeout: Timeout,33 ) -> BaseSocketStream:34 return await self.backend.open_tcp_stream(hostname, port, ssl_context, timeout)3536 async def open_uds_stream(37 self,38 path: str,39 hostname: typing.Optional[str],40 ssl_context: typing.Optional[ssl.SSLContext],41 timeout: TimeoutConfig,41 timeout: Timeout,42 ) -> BaseSocketStream:43 return await self.backend.open_uds_stream(path, hostname, ssl_context, timeout)4445 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:
14 unmodified lines
modified:httpx/concurrency/base.py+6 added-6 removed
1import ssl2import typing3from types import TracebackType45from ..config import PoolLimits, TimeoutConfig5from ..config import PoolLimits, Timeout678def lookup_backend(9 backend: typing.Union[str, "ConcurrencyBackend"] = "auto"
59 unmodified lines
69 def get_http_version(self) -> str:70 raise NotImplementedError() # pragma: no cover7172 async def start_tls(73 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig73 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout74 ) -> "BaseSocketStream":75 raise NotImplementedError() # pragma: no cover7677 async def read(78 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None78 self, n: int, timeout: Timeout = None, flag: typing.Any = None79 ) -> bytes:80 raise NotImplementedError() # pragma: no cover8182 def write_no_block(self, data: bytes) -> None:83 raise NotImplementedError() # pragma: no cover8485 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:85 async def write(self, data: bytes, timeout: Timeout = None) -> None:86 raise NotImplementedError() # pragma: no cover8788 async def close(self) -> None:89 raise NotImplementedError() # pragma: no cover
39 unmodified lines
129 self,130 hostname: str,131 port: int,132 ssl_context: typing.Optional[ssl.SSLContext],133 timeout: TimeoutConfig,133 timeout: Timeout,134 ) -> BaseSocketStream:135 raise NotImplementedError() # pragma: no cover136137 async def open_uds_stream(138 self,139 path: str,140 hostname: typing.Optional[str],141 ssl_context: typing.Optional[ssl.SSLContext],142 timeout: TimeoutConfig,142 timeout: Timeout,143 ) -> BaseSocketStream:144 raise NotImplementedError() # pragma: no cover145146 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:
39 unmodified lines
modified:httpx/concurrency/trio.py+7 added-9 removed
3 unmodified lines
4from types import TracebackType56import trio78from ..config import PoolLimits, TimeoutConfig8from ..config import PoolLimits, Timeout9from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout10from .base import (11 BaseBackgroundManager,12 BaseEvent,
9 unmodified lines
222324class SocketStream(BaseSocketStream):25 def __init__(26 self,27 stream: typing.Union[trio.SocketStream, trio.SSLStream],28 timeout: TimeoutConfig,26 self, stream: typing.Union[trio.SocketStream, trio.SSLStream], timeout: Timeout,27 ) -> None:28 self.stream = stream29 self.timeout = timeout30 self.write_buffer = b""31 self.read_lock = trio.Lock()32 self.write_lock = trio.Lock()3334 async def start_tls(37 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig35 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout36 ) -> "SocketStream":37 # Check that the write buffer is empty. We should never start a TLS stream38 # while there is still pending data to write.39 assert self.write_buffer == b""
18 unmodified lines
58 ident = self.stream.selected_alpn_protocol()59 return "HTTP/2" if ident == "h2" else "HTTP/1.1"6061 async def read(64 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None62 self, n: int, timeout: Timeout = None, flag: TimeoutFlag = None63 ) -> bytes:64 if timeout is None:65 timeout = self.timeout66
28 unmodified lines
95 def write_no_block(self, data: bytes) -> None:96 self.write_buffer += data # pragma: no cover9798 async def write(101 self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None99 self, data: bytes, timeout: Timeout = None, flag: TimeoutFlag = None100 ) -> None:101 if self.write_buffer:102 previous_data = self.write_buffer103 # Reset before recursive call, otherwise we'll go through
69 unmodified lines
173 self,174 hostname: str,175 port: int,176 ssl_context: typing.Optional[ssl.SSLContext],179 timeout: TimeoutConfig,177 timeout: Timeout,178 ) -> SocketStream:179 connect_timeout = _or_inf(timeout.connect_timeout)180181 with trio.move_on_after(connect_timeout) as cancel_scope:
11 unmodified lines
193 self,194 path: str,195 hostname: typing.Optional[str],196 ssl_context: typing.Optional[ssl.SSLContext],199 timeout: TimeoutConfig,197 timeout: Timeout,198 ) -> SocketStream:199 connect_timeout = _or_inf(timeout.connect_timeout)200201 with trio.move_on_after(connect_timeout) as cancel_scope:
75 unmodified lines
modified:httpx/dispatch/connection_pool.py+3 added-3 removed
4 unmodified lines
5 DEFAULT_POOL_LIMITS,6 DEFAULT_TIMEOUT_CONFIG,7 CertTypes,8 PoolLimits,9 TimeoutConfig,9 Timeout,10 TimeoutTypes,11 VerifyTypes,12)13from ..models import Origin, Request, Response
77 unmodified lines
91 uds: typing.Optional[str] = None,92 ):93 self.verify = verify94 self.cert = cert95 self.timeout = TimeoutConfig(timeout)95 self.timeout = Timeout(timeout)96 self.pool_limits = pool_limits97 self.http2 = http298 self.is_closed = False99 self.trust_env = trust_env
46 unmodified lines
146 if connection is None:147 if timeout is None:148 pool_timeout = self.timeout.pool_timeout149 else:150 pool_timeout = TimeoutConfig(timeout).pool_timeout150 pool_timeout = Timeout(timeout).pool_timeout151152 await self.max_connections.acquire(timeout=pool_timeout)153 connection = HTTPConnection(154 origin,
50 unmodified lines
modified:httpx/dispatch/connection.py+3 added-3 removed
5 unmodified lines
6from ..config import (7 DEFAULT_TIMEOUT_CONFIG,8 CertTypes,9 SSLConfig,10 TimeoutConfig,10 Timeout,11 TimeoutTypes,12 VerifyTypes,13)14from ..models import Origin, Request, Response
23 unmodified lines
38 uds: typing.Optional[str] = None,39 ):40 self.origin = Origin(origin) if isinstance(origin, str) else origin41 self.ssl = SSLConfig(cert=cert, verify=verify, trust_env=trust_env)42 self.timeout = TimeoutConfig(timeout)42 self.timeout = Timeout(timeout)43 self.http2 = http244 self.backend = lookup_backend(backend)45 self.release_func = release_func46 self.uds = uds
24 unmodified lines
71 cert: CertTypes = None,72 timeout: TimeoutTypes = None,73 ) -> None:74 ssl = self.ssl.with_overrides(verify=verify, cert=cert)75 timeout = self.timeout if timeout is None else TimeoutConfig(timeout)75 timeout = self.timeout if timeout is None else Timeout(timeout)7677 host = self.origin.host78 port = self.origin.port79 ssl_context = await self.get_ssl_context(ssl)
68 unmodified lines
modified:httpx/dispatch/http11.py+8 added-10 removed
1 unmodified line
23import h1145from ..concurrency.base import BaseSocketStream, TimeoutFlag6from ..config import TimeoutConfig, TimeoutTypes6from ..config import Timeout, TimeoutTypes7from ..exceptions import ConnectionClosed, ProtocolError8from ..models import Request, Response9from ..utils import get_logger10
29 unmodified lines
40 self.h11_state = h11.Connection(our_role=h11.CLIENT)41 self.timeout_flag = TimeoutFlag()4243 async def send(self, request: Request, timeout: TimeoutTypes = None) -> Response:44 timeout = None if timeout is None else TimeoutConfig(timeout)44 timeout = None if timeout is None else Timeout(timeout)4546 await self._send_request(request, timeout)47 await self._send_request_body(request, timeout)48 http_version, status_code, headers = await self._receive_response(timeout)
17 unmodified lines
66 # Premature client disconnect67 pass68 await self.stream.close()6970 async def _send_request(71 self, request: Request, timeout: TimeoutConfig = None72 ) -> None:70 async def _send_request(self, request: Request, timeout: Timeout = None) -> None:71 """72 Send the request method, URL, and headers to the network.73 """74 logger.trace(
8 unmodified lines
83 event = h11.Request(method=method, target=target, headers=headers)84 await self._send_event(event, timeout)8586 async def _send_request_body(89 self, request: Request, timeout: TimeoutConfig = None87 self, request: Request, timeout: Timeout = None88 ) -> None:89 """90 Send the request body to the network.91 """
15 unmodified lines
107 finally:108 # Once we've sent the request, we enable read timeouts.109 self.timeout_flag.set_read_timeouts()110113 async def _send_event(self, event: H11Event, timeout: TimeoutConfig = None) -> None:111 async def _send_event(self, event: H11Event, timeout: Timeout = None) -> None:112 """113 Send a single `h11` event to the network, waiting for the data to114 drain before returning.115 """116 bytes_to_send = self.h11_state.send(event)117 await self.stream.write(bytes_to_send, timeout)118119 async def _receive_response(122 self, timeout: TimeoutConfig = None120 self, timeout: Timeout = None121 ) -> typing.Tuple[str, int, typing.List[typing.Tuple[bytes, bytes]]]:122 """123 Read the response status and headers from the network.124 """
10 unmodified lines
135 http_version = "HTTP/%s" % event.http_version.decode("latin-1", errors="ignore")136 return http_version, event.status_code, event.headers137138 async def _receive_response_data(141 self, timeout: TimeoutConfig = None139 self, timeout: Timeout = None140 ) -> typing.AsyncIterator[bytes]:141 """142 Read the response data from the network.143 """
4 unmodified lines
148 else:149 assert isinstance(event, h11.EndOfMessage) or event is h11.PAUSED150 break # pragma: no cover151154 async def _receive_event(self, timeout: TimeoutConfig = None) -> H11Event:152 async def _receive_event(self, timeout: Timeout = None) -> H11Event:153 """154 Read a single `h11` event, reading more data from the network if needed.155 """156 while True:
55 unmodified lines
modified:httpx/dispatch/http2.py+9 added-11 removed
10 unmodified lines
11 ConcurrencyBackend,12 TimeoutFlag,13 lookup_backend,14)15from ..config import TimeoutConfig, TimeoutTypes15from ..config import Timeout, TimeoutTypes16from ..exceptions import ProtocolError17from ..models import Request, Response18from ..utils import get_logger19
18 unmodified lines
38 self.initialized = False39 self.window_update_received = {} # type: typing.Dict[int, BaseEvent]4041 async def send(self, request: Request, timeout: TimeoutTypes = None) -> Response:42 timeout = None if timeout is None else TimeoutConfig(timeout)42 timeout = None if timeout is None else Timeout(timeout)4344 # Start sending the request.45 if not self.initialized:46 self.initiate_connection()
49 unmodified lines
96 data_to_send = self.h2_state.data_to_send()97 self.stream.write_no_block(data_to_send)98 self.initialized = True99100 async def send_headers(101 self, request: Request, timeout: TimeoutConfig = None102 ) -> int:100 async def send_headers(self, request: Request, timeout: Timeout = None) -> int:101 stream_id = self.h2_state.get_next_available_stream_id()102 headers = [103 (b":method", request.method.encode("ascii")),104 (b":authority", request.url.authority.encode("ascii")),
16 unmodified lines
121 async def send_request_data(122 self,123 stream_id: int,124 stream: typing.AsyncIterator[bytes],127 timeout: TimeoutConfig = None,125 timeout: Timeout = None,126 ) -> None:127 try:128 async for data in stream:129 await self.send_data(stream_id, data, timeout)
2 unmodified lines
132 # Once we've sent the request we should enable read timeouts.133 self.timeout_flags[stream_id].set_read_timeouts()134135 async def send_data(138 self, stream_id: int, data: bytes, timeout: TimeoutConfig = None136 self, stream_id: int, data: bytes, timeout: Timeout = None137 ) -> None:138 while data:139 # The data will be divided into frames to send based on the flow control140 # window and the maximum frame size. Because the flow control window
15 unmodified lines
156 self.h2_state.send_data(stream_id, chunk)157 data_to_send = self.h2_state.data_to_send()158 await self.stream.write(data_to_send, timeout)159162 async def end_stream(self, stream_id: int, timeout: TimeoutConfig = None) -> None:160 async def end_stream(self, stream_id: int, timeout: Timeout = None) -> None:161 logger.trace(f"end_stream stream_id={stream_id}")162 self.h2_state.end_stream(stream_id)163 data_to_send = self.h2_state.data_to_send()164 await self.stream.write(data_to_send, timeout)165166 async def receive_response(169 self, stream_id: int, timeout: TimeoutConfig = None167 self, stream_id: int, timeout: Timeout = None168 ) -> typing.Tuple[int, typing.List[typing.Tuple[bytes, bytes]]]:169 """170 Read the response status and headers from the network.171 """
15 unmodified lines
187188 return (status_code, headers)189190 async def body_iter(193 self, stream_id: int, timeout: TimeoutConfig = None191 self, stream_id: int, timeout: Timeout = None192 ) -> typing.AsyncIterator[bytes]:193 while True:194 event = await self.receive_event(stream_id, timeout)195 if isinstance(event, h2.events.DataReceived):
4 unmodified lines
200 elif isinstance(event, (h2.events.StreamEnded, h2.events.StreamReset)):201 break202203 async def receive_event(206 self, stream_id: int, timeout: TimeoutConfig = None204 self, stream_id: int, timeout: Timeout = None205 ) -> h2.events.Event:206 while not self.events[stream_id]:207 flag = self.timeout_flags[stream_id]208 data = await self.stream.read(self.READ_NUM_BYTES, timeout, flag=flag)
45 unmodified lines
modified:httpx/__init__.py+4 added-2 removed
12 unmodified lines
13 USER_AGENT,14 CertTypes,15 PoolLimits,16 SSLConfig,17 Timeout,18 TimeoutConfig,19 TimeoutTypes,20 VerifyTypes,21)
13 unmodified lines
35 ProxyError,36 ReadTimeout,37 RedirectBodyUnavailable,38 RedirectLoop,39 RequestTimeout,40 ResponseClosed,41 ResponseNotRead,42 StreamConsumed,41 Timeout,43 TooManyRedirects,44 WriteTimeout,45)46from .models import (
35 unmodified lines
82 "USER_AGENT",83 "CertTypes",84 "PoolLimits",85 "SSLConfig",86 "Timeout",87 "TimeoutConfig",88 "VerifyTypes",89 "HTTPConnection",90 "BasePoolSemaphore",
15 unmodified lines
106 "ResponseClosed",107 "ResponseNotRead",108 "StreamConsumed",109 "ProxyError",108 "Timeout",110 "TooManyRedirects",111 "WriteTimeout",112 "BaseSocketStream",113 "ConcurrencyBackend",
12 unmodified lines
126 "QueryParams",127 "QueryParamTypes",128 "Request",129 "RequestData",130 "RequestTimeout",131 "Response",132 "ResponseContent",133 "RequestFiles",134 "DigestAuth",
1 unmodified line
modified:httpx/config.py+7 added-6 removed
8 unmodified lines
9from .utils import get_ca_bundle_from_env, get_logger1011CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]12VerifyTypes = typing.Union[str, bool, ssl.SSLContext]13TimeoutTypes = typing.Union[14 float, typing.Tuple[float, float, float, float], "TimeoutConfig"15]13TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float, float], "Timeout"]141516USER_AGENT = f"python-httpx/{__version__}"17
182 unmodified lines
200 password=self.cert[2], # type: ignore201 )202203206class TimeoutConfig:204class Timeout:205 """206 Timeout values.207 """208
16 unmodified lines
225 assert connect_timeout is None226 assert read_timeout is None227 assert write_timeout is None228 assert pool_timeout is None231 if isinstance(timeout, TimeoutConfig):229 if isinstance(timeout, Timeout):230 self.connect_timeout = timeout.connect_timeout231 self.read_timeout = timeout.read_timeout232 self.write_timeout = timeout.write_timeout233 self.pool_timeout = timeout.pool_timeout
62 unmodified lines
296 f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit})"297 )298299300TimeoutConfig = Timeout # Synonym for backwards compat301302303DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)303DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)304DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0)305DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)306DEFAULT_CA_BUNDLE_PATH = Path(certifi.where())307DEFAULT_MAX_REDIRECTS = 20
modified:httpx/exceptions.py+5 added-5 removed
18 unmodified lines
1920# Timeout exceptions...212223class Timeout(HTTPError):23class RequestTimeout(HTTPError):24 """25 A base class for all timeouts.26 """272829class ConnectTimeout(Timeout):29class ConnectTimeout(RequestTimeout):30 """31 Timeout while establishing a connection.32 """333435class ReadTimeout(Timeout):35class ReadTimeout(RequestTimeout):36 """37 Timeout while reading response data.38 """394041class WriteTimeout(Timeout):41class WriteTimeout(RequestTimeout):42 """43 Timeout while writing request data.44 """454647class PoolTimeout(Timeout):47class PoolTimeout(RequestTimeout):48 """49 Timeout while waiting to acquire a connection from the pool.50 """51
108 unmodified lines
modified:tests/dispatch/utils.py+5 added-5 removed
3 unmodified lines
4import h2.config5import h2.connection6import h2.events78from httpx import AsyncioBackend, BaseSocketStream, Request, TimeoutConfig8from httpx import AsyncioBackend, BaseSocketStream, Request, Timeout9from tests.concurrency import sleep101112class MockHTTP2Backend:
6 unmodified lines
19 self,20 hostname: str,21 port: int,22 ssl_context: typing.Optional[ssl.SSLContext],23 timeout: TimeoutConfig,23 timeout: Timeout,24 ) -> BaseSocketStream:25 self.server = MockHTTP2Server(self.app, backend=self.backend)26 return self.server27
148 unmodified lines
176 self,177 hostname: str,178 port: int,179 ssl_context: typing.Optional[ssl.SSLContext],180 timeout: TimeoutConfig,180 timeout: Timeout,181 ) -> BaseSocketStream:182 self.received_data.append(183 b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)184 )
8 unmodified lines
193 def __init__(self, backend: MockRawSocketBackend):194 self.backend = backend195196 async def start_tls(197 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig197 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout198 ) -> BaseSocketStream:199 self.backend.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())200 return MockRawSocketStream(self.backend)201
2 unmodified lines
204205 def write_no_block(self, data: bytes) -> None:206 self.backend.received_data.append(data)207208 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:208 async def write(self, data: bytes, timeout: Timeout = None) -> None:209 if data:210 self.write_no_block(data)211212 async def read(self, n, timeout, flag=None) -> bytes:
10 unmodified lines
modified:tests/test_concurrency.py+4 added-4 removed
1import pytest2import trio34from httpx import AsyncioBackend, SSLConfig, TimeoutConfig4from httpx import AsyncioBackend, SSLConfig, Timeout5from httpx.concurrency.trio import TrioBackend6from tests.concurrency import run_concurrently78
31 unmodified lines
40 ],41)42async def test_start_tls_on_tcp_socket_stream(https_server, backend, get_cipher):43 ctx = SSLConfig().load_ssl_context_no_verify()44 timeout = TimeoutConfig(5)44 timeout = Timeout(5)4546 stream = await backend.open_tcp_stream(47 https_server.url.host, https_server.url.port, None, timeout48 )
23 unmodified lines
72 ],73)74async def test_start_tls_on_uds_socket_stream(https_uds_server, backend, get_cipher):75 ctx = SSLConfig().load_ssl_context_no_verify()76 timeout = TimeoutConfig(5)76 timeout = Timeout(5)7778 stream = await backend.open_uds_stream(79 https_uds_server.config.uds, https_uds_server.url.host, None, timeout80 )
19 unmodified lines
100 """101 Regression test for: https://github.com/encode/httpx/issues/527102 """103 stream = await backend.open_tcp_stream(104 server.url.host, server.url.port, ssl_context=None, timeout=TimeoutConfig(5)104 server.url.host, server.url.port, ssl_context=None, timeout=Timeout(5)105 )106 try:107 await stream.write(b"GET / HTTP/1.1\r\n\r\n")108 await run_concurrently(
4 unmodified lines
modified:tests/test_config.py+15 added-15 removed
132 unmodified lines
133 assert limits == httpx.PoolLimits(hard_limit=100)134135136def test_timeout_eq():137 timeout = httpx.TimeoutConfig(timeout=5.0)138 assert timeout == httpx.TimeoutConfig(timeout=5.0)137 timeout = httpx.Timeout(timeout=5.0)138 assert timeout == httpx.Timeout(timeout=5.0)139140141def test_timeout_from_nothing():142 timeout = httpx.TimeoutConfig()142 timeout = httpx.Timeout()143 assert timeout.connect_timeout is None144 assert timeout.read_timeout is None145 assert timeout.write_timeout is None146 assert timeout.pool_timeout is None147148149def test_timeout_from_none():150 timeout = httpx.TimeoutConfig(timeout=None)151 assert timeout == httpx.TimeoutConfig()150 timeout = httpx.Timeout(timeout=None)151 assert timeout == httpx.Timeout()152153154def test_timeout_from_one_none_value():155 timeout = httpx.TimeoutConfig(read_timeout=None)156 assert timeout == httpx.TimeoutConfig()155 timeout = httpx.Timeout(read_timeout=None)156 assert timeout == httpx.Timeout()157158159def test_timeout_from_tuple():160 timeout = httpx.TimeoutConfig(timeout=(5.0, 5.0, 5.0, 5.0))161 assert timeout == httpx.TimeoutConfig(timeout=5.0)160 timeout = httpx.Timeout(timeout=(5.0, 5.0, 5.0, 5.0))161 assert timeout == httpx.Timeout(timeout=5.0)162163164def test_timeout_from_config_instance():165 timeout = httpx.TimeoutConfig(timeout=5.0)166 assert httpx.TimeoutConfig(timeout) == httpx.TimeoutConfig(timeout=5.0)165 timeout = httpx.Timeout(timeout=5.0)166 assert httpx.Timeout(timeout) == httpx.Timeout(timeout=5.0)167168169def test_timeout_repr():170 timeout = httpx.TimeoutConfig(timeout=5.0)171 assert repr(timeout) == "TimeoutConfig(timeout=5.0)"170 timeout = httpx.Timeout(timeout=5.0)171 assert repr(timeout) == "Timeout(timeout=5.0)"172173 timeout = httpx.TimeoutConfig(read_timeout=5.0)173 timeout = httpx.Timeout(read_timeout=5.0)174 assert repr(timeout) == (175 "TimeoutConfig(connect_timeout=None, read_timeout=5.0, "175 "Timeout(connect_timeout=None, read_timeout=5.0, "176 "write_timeout=None, pool_timeout=None)"177 )178179
28 unmodified lines
modified:tests/test_timeouts.py+5 added-5 removed
4 unmodified lines
5 ConnectTimeout,6 PoolLimits,7 PoolTimeout,8 ReadTimeout,9 TimeoutConfig,9 Timeout,10 WriteTimeout,11)121314async def test_read_timeout(server, backend):15 timeout = TimeoutConfig(read_timeout=1e-6)15 timeout = Timeout(read_timeout=1e-6)1617 async with Client(timeout=timeout, backend=backend) as client:18 with pytest.raises(ReadTimeout):19 await client.get(server.url.copy_with(path="/slow_response"))202122async def test_write_timeout(server, backend):23 timeout = TimeoutConfig(write_timeout=1e-6)23 timeout = Timeout(write_timeout=1e-6)2425 async with Client(timeout=timeout, backend=backend) as client:26 with pytest.raises(WriteTimeout):27 data = b"*" * 1024 * 1024 * 10028 await client.put(server.url.copy_with(path="/slow_response"), data=data)293031async def test_connect_timeout(server, backend):32 timeout = TimeoutConfig(connect_timeout=1e-6)32 timeout = Timeout(connect_timeout=1e-6)3334 async with Client(timeout=timeout, backend=backend) as client:35 with pytest.raises(ConnectTimeout):36 # See https://stackoverflow.com/questions/100841/
1 unmodified line
383940async def test_pool_timeout(server, backend):41 pool_limits = PoolLimits(hard_limit=1)42 timeout = TimeoutConfig(pool_timeout=1e-4)42 timeout = Timeout(pool_timeout=1e-4)4344 async with Client(45 pool_limits=pool_limits, timeout=timeout, backend=backend46 ) as client:
6 unmodified lines