Allow default+override timeout style (#593)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Allow styles like: httpx.Timeout(5.0, pool_timeout=None) * Update timeout docs * Minor tweaks to sub headings in timeout docs * Fixing up Timeout docs * RequestTimeout -> TimeoutException * Tweak timeout docs
authored by Tom Christie · committed by GitHub · parent 81edb1b · Browse files · 7 files·+123 added−96 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+123 added−96 removed
- tests:+10 added−0 removed
- other:+113 added−96 removed
Provenance
- Commit
2f54b20- Tree
c5ef71c- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
81edb1b
7 files changed+123 added−96 removed
modified:docs/advanced.md+47 added-52 removed
248 unmodified lines249 Per request proxy configuration, i.e. `client.get(url, proxies=...)`,250 has not been implemented yet. To use proxies you must pass the proxy251 information at `Client` initialization.252 253-## Timeout fine-tuning253+## Timeout Configuration254 255-HTTPX offers various request timeout management options. Three types of timeouts256-are available: **connect** timeouts, **write** timeouts and **read** timeouts.255+HTTPX is careful to enforce timeouts everywhere by default.256 258-* The **connect timeout** specifies the maximum amount of time to wait until259-a connection to the requested host is established. If HTTPX is unable to connect260-within this time frame, a `ConnectTimeout` exception is raised.261-* The **write timeout** specifies the maximum duration to wait for a chunk of262-data to be sent (for example, a chunk of the request body). If HTTPX is unable263-to send data within this time frame, a `WriteTimeout` exception is raised.264-* The **read timeout** specifies the maximum duration to wait for a chunk of265-data to be received (for example, a chunk of the response body). If HTTPX is266-unable to receive data within this time frame, a `ReadTimeout` exception is raised.257+The default behavior is to raise a `TimeoutException` after 5 seconds of258+network inactivity.259 268-### Setting timeouts260+### Setting and disabling timeouts261 270-You can set timeouts on two levels:262+You can set timeouts for an individual request:263 272-- For a given request:273-264 ```python275-# Using top-level API276-await httpx.get('http://example.com/api/v1/example', timeout=5)265+# Using the top-level API:266+await httpx.get('http://example.com/api/v1/example', timeout=10.0)267 278-# Or, with a client:268+# Using a client instance:269 async with httpx.Client() as client:280- await client.get("http://example.com/api/v1/example", timeout=5)270+ await client.get("http://example.com/api/v1/example", timeout=10.0)271 ```272 283-- On a client instance, which results in the given `timeout` being used as a default for requests made with this client:273+Or disable timeouts for an individual request:274 275 ```python286-async with httpx.Client(timeout=5) as client:287- await client.get('http://example.com/api/v1/example')276+# Using the top-level API:277+await httpx.get('http://example.com/api/v1/example', timeout=None)278+279+# Using a client instance:280+async with httpx.Client() as client:281+ await client.get("http://example.com/api/v1/example", timeout=None)282 ```283 290-Besides, you can pass timeouts in two forms:284+### Setting a default timeout on a client285 292-- A number, which sets the read, write and connect timeouts to the same value, as in the examples above.293-- A `Timeout` instance, which allows to define the read, write and connect timeouts independently:286+You can set a timeout on a client instance, which results in the given287+`timeout` being used as the default for requests made with this client:288 289 ```python296-timeout = httpx.Timeout(297- connect_timeout=5,298- read_timeout=10,299- write_timeout=15300-)301-302-resp = await httpx.get('http://example.com/api/v1/example', timeout=timeout)290+client = httpx.Client() # Use a default 5s timeout everywhere.291+client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.292+client = httpx.Client(timeout=None) # Disable all timeouts by default.293 ```294 305-### Default timeouts295+### Fine tuning the configuration296 307-By default all types of timeouts are set to 5 second.297+HTTPX also allows you to specify the timeout behavior in more fine grained detail.298 309-### Disabling timeouts299+There are four different types of timeouts that may occur. These are **connect**,300+**read**, **write**, and **pool** timeouts.301 311-To disable timeouts, you can pass `None` as a timeout parameter.312-Note that currently this is not supported by the top-level API.302+* The **connect timeout** specifies the maximum amount of time to wait until303+a connection to the requested host is established. If HTTPX is unable to connect304+within this time frame, a `ConnectTimeout` exception is raised.305+* The **read timeout** specifies the maximum duration to wait for a chunk of306+data to be received (for example, a chunk of the response body). If HTTPX is307+unable to receive data within this time frame, a `ReadTimeout` exception is raised.308+* The **write timeout** specifies the maximum duration to wait for a chunk of309+data to be sent (for example, a chunk of the request body). If HTTPX is unable310+to send data within this time frame, a `WriteTimeout` exception is raised.311+* The **pool timeout** specifies the maximum duration to wait for acquiring312+a connection from the connection pool. If HTTPX is unable to acquire a connection313+within this time frame, a `PoolTimeout` exception is raised. A related314+configuration here is the maximum number of allowable connections in the315+connection pool, which is configured by the `pool_limits`.316 317+You can configure the timeout behavior for any of these values...318+319 ```python315-url = "http://example.com/api/v1/delay/10"320+# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.321+timeout = httpx.Timeout(10.0, connect_timeout=60.0)322+client = httpx.Client(timeout=timeout)323 317-await httpx.get(url, timeout=None) # Times out after 5s318-319-320-async with httpx.Client(timeout=None) as client:321- await client.get(url) # Does not timeout, returns after 10s322-323-324-timeout = httpx.Timeout(325- connect_timeout=5,326- read_timeout=None,327- write_timeout=5328-)329-await httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s324+response = await client.get('http://example.com/')325 ```326 327 ## Multipart file encoding328 102 unmodified linesmodified:docs/quickstart.md+6 added
379 unmodified lines380 ```python381 >>> await httpx.get('https://github.com/', timeout=0.001)382 ```383 384+You can also disable the timeout behavior completely...385+386+```python387+>>> await httpx.get('https://github.com/', timeout=None)388+```389+390 For advanced timeout management, see [Timeout fine-tuning](https://www.encode.io/httpx/advanced/#timeout-fine-tuning).391 392 ## Authentication393 20 unmodified linesmodified:httpx/__init__.py+2 added-2 removed
34 unmodified lines35 ProxyError,36 ReadTimeout,37 RedirectBodyUnavailable,38 RedirectLoop,39- RequestTimeout,39 ResponseClosed,40 ResponseNotRead,41 StreamConsumed,42+ TimeoutException,43 TooManyRedirects,44 WriteTimeout,45 )46 from .models import (79 unmodified lines126 "QueryParams",127 "QueryParamTypes",128 "Request",129 "RequestData",130- "RequestTimeout",130+ "TimeoutException",131 "Response",132 "ResponseContent",133 "RequestFiles",134 "DigestAuth",1 unmodified linemodified:httpx/client.py+2 added-7 removed
8 unmodified lines9 from .config import (10 DEFAULT_MAX_REDIRECTS,11 DEFAULT_POOL_LIMITS,12 DEFAULT_TIMEOUT_CONFIG,13+ UNSET,14 CertTypes,15 PoolLimits,16 Timeout,17 TimeoutTypes,18+ UnsetType,19 VerifyTypes,20 )21 from .dispatch.asgi import ASGIDispatch22 from .dispatch.base import Dispatcher28 unmodified lines51 52 logger = get_logger(__name__)53 54 53-class UnsetType:54- pass # pragma: nocover55-56-57-UNSET = UnsetType()58-59-55 class Client:56 """57 An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.58 808 unmodified linesmodified:httpx/config.py+51 added-30 removed
36 unmodified lines37 38 logger = get_logger(__name__)39 40 41+class UnsetType:42+ pass # pragma: nocover43+44+45+UNSET = UnsetType()46+47+48 class SSLConfig:49 """50 SSL Configuration.51 """157 unmodified lines209 210 211 class Timeout:212 """206- Timeout values.213+ Timeout configuration.214+215+ **Usage**:216+217+ Timeout() # No timeout.218+ Timeout(5.0) # 5s timeout on all operations.219+ Timeout(connect_timeout=5.0) # 5s timeout on connect, no other timeouts.220+ Timeout(5.0, connect_timeout=10.0) # 10s timeout on connect. 5s timeout elsewhere.221+ Timeout(5.0, pool_timeout=None) # No timeout on acquiring connection from pool.222+ # 5s timeout elsewhere.223 """224 225 def __init__(226 self,227 timeout: TimeoutTypes = None,228 *,213- connect_timeout: float = None,214- read_timeout: float = None,215- write_timeout: float = None,216- pool_timeout: float = None,229+ connect_timeout: typing.Union[None, float, UnsetType] = UNSET,230+ read_timeout: typing.Union[None, float, UnsetType] = UNSET,231+ write_timeout: typing.Union[None, float, UnsetType] = UNSET,232+ pool_timeout: typing.Union[None, float, UnsetType] = UNSET,233 ):218- if timeout is None:219- self.connect_timeout = connect_timeout220- self.read_timeout = read_timeout221- self.write_timeout = write_timeout222- self.pool_timeout = pool_timeout234+ if isinstance(timeout, Timeout):235+ # Passed as a single explicit Timeout.236+ assert connect_timeout is UNSET237+ assert read_timeout is UNSET238+ assert write_timeout is UNSET239+ assert pool_timeout is UNSET240+ self.connect_timeout = (241+ timeout.connect_timeout242+ ) # type: typing.Optional[float]243+ self.read_timeout = timeout.read_timeout # type: typing.Optional[float]244+ self.write_timeout = timeout.write_timeout # type: typing.Optional[float]245+ self.pool_timeout = timeout.pool_timeout # type: typing.Optional[float]246+ elif isinstance(timeout, tuple):247+ # Passed as a tuple.248+ self.connect_timeout = timeout[0]249+ self.read_timeout = timeout[1]250+ self.write_timeout = None if len(timeout) < 3 else timeout[2]251+ self.pool_timeout = None if len(timeout) < 4 else timeout[3]252 else:224- # Specified as a single timeout value225- assert connect_timeout is None226- assert read_timeout is None227- assert write_timeout is None228- assert pool_timeout is None229- 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_timeout234- elif isinstance(timeout, tuple):235- self.connect_timeout = timeout[0]236- self.read_timeout = timeout[1]237- self.write_timeout = None if len(timeout) < 3 else timeout[2]238- self.pool_timeout = None if len(timeout) < 4 else timeout[3]239- else:240- self.connect_timeout = timeout241- self.read_timeout = timeout242- self.write_timeout = timeout243- self.pool_timeout = timeout253+ self.connect_timeout = (254+ timeout if isinstance(connect_timeout, UnsetType) else connect_timeout255+ )256+ self.read_timeout = (257+ timeout if isinstance(read_timeout, UnsetType) else read_timeout258+ )259+ self.write_timeout = (260+ timeout if isinstance(write_timeout, UnsetType) else write_timeout261+ )262+ self.pool_timeout = (263+ timeout if isinstance(pool_timeout, UnsetType) else pool_timeout264+ )265 266 def __eq__(self, other: typing.Any) -> bool:267 return (268 isinstance(other, self.__class__)60 unmodified linesmodified:httpx/exceptions.py+5 added-5 removed
18 unmodified lines19 20 # Timeout exceptions...21 22 23-class RequestTimeout(HTTPError):23+class TimeoutException(HTTPError):24 """25 A base class for all timeouts.26 """27 28 29-class ConnectTimeout(RequestTimeout):29+class ConnectTimeout(TimeoutException):30 """31 Timeout while establishing a connection.32 """33 34 35-class ReadTimeout(RequestTimeout):35+class ReadTimeout(TimeoutException):36 """37 Timeout while reading response data.38 """39 40 41-class WriteTimeout(RequestTimeout):41+class WriteTimeout(TimeoutException):42 """43 Timeout while writing request data.44 """45 46 47-class PoolTimeout(RequestTimeout):47+class PoolTimeout(TimeoutException):48 """49 Timeout while waiting to acquire a connection from the pool.50 """51 108 unmodified linesmodified:tests/test_config.py+10 added
154 unmodified lines155 timeout = httpx.Timeout(read_timeout=None)156 assert timeout == httpx.Timeout()157 158 159+def test_timeout_from_one_value():160+ timeout = httpx.Timeout(read_timeout=5.0)161+ assert timeout == httpx.Timeout(timeout=(None, 5.0, None, None))162+163+164+def test_timeout_from_one_value_and_default():165+ timeout = httpx.Timeout(5.0, pool_timeout=60.0)166+ assert timeout == httpx.Timeout(timeout=(5.0, 5.0, 5.0, 60.0))167+168+169 def test_timeout_from_tuple():170 timeout = httpx.Timeout(timeout=(5.0, 5.0, 5.0, 5.0))171 assert timeout == httpx.Timeout(timeout=5.0)172 45 unmodified lines