Skip to content
Myr

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

7 files+123 added−96 removed

modified:docs/advanced.md+47 added-52 removed
248 unmodified lines
249 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.252253## Timeout fine-tuning253## Timeout Configuration254255HTTPX offers various request timeout management options. Three types of timeouts256are available: **connect** timeouts, **write** timeouts and **read** timeouts.255HTTPX is careful to enforce timeouts everywhere by default.256258* The **connect timeout** specifies the maximum amount of time to wait until259a connection to the requested host is established. If HTTPX is unable to connect260within this time frame, a `ConnectTimeout` exception is raised.261* The **write timeout** specifies the maximum duration to wait for a chunk of262data to be sent (for example, a chunk of the request body). If HTTPX is unable263to send data within this time frame, a `WriteTimeout` exception is raised.264* The **read timeout** specifies the maximum duration to wait for a chunk of265data to be received (for example, a chunk of the response body). If HTTPX is266unable to receive data within this time frame, a `ReadTimeout` exception is raised.257The default behavior is to raise a `TimeoutException` after 5 seconds of258network inactivity.259268### Setting timeouts260### Setting and disabling timeouts261270You can set timeouts on two levels:262You can set timeouts for an individual request:263272- For a given request:273264```python275# Using top-level API276await httpx.get('http://example.com/api/v1/example', timeout=5)265# Using the top-level API:266await httpx.get('http://example.com/api/v1/example', timeout=10.0)267278# Or, with a client:268# Using a client instance:269async 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```272283- On a client instance, which results in the given `timeout` being used as a default for requests made with this client:273Or disable timeouts for an individual request:274275```python286async with httpx.Client(timeout=5) as client:287 await client.get('http://example.com/api/v1/example')276# Using the top-level API:277await httpx.get('http://example.com/api/v1/example', timeout=None)278279# Using a client instance:280async with httpx.Client() as client:281 await client.get("http://example.com/api/v1/example", timeout=None)282```283290Besides, you can pass timeouts in two forms:284### Setting a default timeout on a client285292- 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:286You 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:288289```python296timeout = httpx.Timeout(297 connect_timeout=5,298 read_timeout=10,299 write_timeout=15300)301302resp = await httpx.get('http://example.com/api/v1/example', timeout=timeout)290client = httpx.Client() # Use a default 5s timeout everywhere.291client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.292client = httpx.Client(timeout=None) # Disable all timeouts by default.293```294305### Default timeouts295### Fine tuning the configuration296307By default all types of timeouts are set to 5 second.297HTTPX also allows you to specify the timeout behavior in more fine grained detail.298309### Disabling timeouts299There are four different types of timeouts that may occur. These are **connect**,300**read**, **write**, and **pool** timeouts.301311To disable timeouts, you can pass `None` as a timeout parameter.312Note that currently this is not supported by the top-level API.302* The **connect timeout** specifies the maximum amount of time to wait until303a connection to the requested host is established. If HTTPX is unable to connect304within this time frame, a `ConnectTimeout` exception is raised.305* The **read timeout** specifies the maximum duration to wait for a chunk of306data to be received (for example, a chunk of the response body). If HTTPX is307unable 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 of309data to be sent (for example, a chunk of the request body). If HTTPX is unable310to send data within this time frame, a `WriteTimeout` exception is raised.311* The **pool timeout** specifies the maximum duration to wait for acquiring312a connection from the connection pool. If HTTPX is unable to acquire a connection313within this time frame, a `PoolTimeout` exception is raised. A related314configuration here is the maximum number of allowable connections in the315connection pool, which is configured by the `pool_limits`.316317You can configure the timeout behavior for any of these values...318319```python315url = "http://example.com/api/v1/delay/10"320# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.321timeout = httpx.Timeout(10.0, connect_timeout=60.0)322client = httpx.Client(timeout=timeout)323317await httpx.get(url, timeout=None) # Times out after 5s318319320async with httpx.Client(timeout=None) as client:321 await client.get(url) # Does not timeout, returns after 10s322323324timeout = httpx.Timeout(325 connect_timeout=5,326 read_timeout=None,327 write_timeout=5328)329await httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s324response = await client.get('http://example.com/')325```326327## Multipart file encoding328
102 unmodified lines
modified:docs/quickstart.md+6 added
379 unmodified lines
380```python381>>> await httpx.get('https://github.com/', timeout=0.001)382```383384You can also disable the timeout behavior completely...385386```python387>>> await httpx.get('https://github.com/', timeout=None)388```389390For advanced timeout management, see [Timeout fine-tuning](https://www.encode.io/httpx/advanced/#timeout-fine-tuning).391392## Authentication393
20 unmodified lines
modified:httpx/__init__.py+2 added-2 removed
34 unmodified lines
35 ProxyError,36 ReadTimeout,37 RedirectBodyUnavailable,38 RedirectLoop,39 RequestTimeout,39 ResponseClosed,40 ResponseNotRead,41 StreamConsumed,42 TimeoutException,43 TooManyRedirects,44 WriteTimeout,45)46from .models import (
79 unmodified lines
126 "QueryParams",127 "QueryParamTypes",128 "Request",129 "RequestData",130 "RequestTimeout",130 "TimeoutException",131 "Response",132 "ResponseContent",133 "RequestFiles",134 "DigestAuth",
1 unmodified line
modified:httpx/client.py+2 added-7 removed
8 unmodified lines
9from .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)21from .dispatch.asgi import ASGIDispatch22from .dispatch.base import Dispatcher
28 unmodified lines
5152logger = get_logger(__name__)535453class UnsetType:54 pass # pragma: nocover555657UNSET = UnsetType()585955class Client:56 """57 An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.58
808 unmodified lines
modified:httpx/config.py+51 added-30 removed
36 unmodified lines
3738logger = get_logger(__name__)394041class UnsetType:42 pass # pragma: nocover434445UNSET = UnsetType()464748class SSLConfig:49 """50 SSL Configuration.51 """
157 unmodified lines
209210211class Timeout:212 """206 Timeout values.213 Timeout configuration.214215 **Usage**:216217 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 """224225 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 )265266 def __eq__(self, other: typing.Any) -> bool:267 return (268 isinstance(other, self.__class__)
60 unmodified lines
modified:httpx/exceptions.py+5 added-5 removed
18 unmodified lines
1920# Timeout exceptions...212223class RequestTimeout(HTTPError):23class TimeoutException(HTTPError):24 """25 A base class for all timeouts.26 """272829class ConnectTimeout(RequestTimeout):29class ConnectTimeout(TimeoutException):30 """31 Timeout while establishing a connection.32 """333435class ReadTimeout(RequestTimeout):35class ReadTimeout(TimeoutException):36 """37 Timeout while reading response data.38 """394041class WriteTimeout(RequestTimeout):41class WriteTimeout(TimeoutException):42 """43 Timeout while writing request data.44 """454647class PoolTimeout(RequestTimeout):47class PoolTimeout(TimeoutException):48 """49 Timeout while waiting to acquire a connection from the pool.50 """51
108 unmodified lines
modified:tests/test_config.py+10 added
154 unmodified lines
155 timeout = httpx.Timeout(read_timeout=None)156 assert timeout == httpx.Timeout()157158159def test_timeout_from_one_value():160 timeout = httpx.Timeout(read_timeout=5.0)161 assert timeout == httpx.Timeout(timeout=(None, 5.0, None, None))162163164def 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))167168169def 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