Skip to content
Myr

Better HTTP/2 defaults. (#584)

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

* Simplify HTTP version config, and switch HTTP/2 off by default * HTTP/2 docs * HTTP/2 interlinking in docs

authored by Tom Christie · committed by GitHub · parent 12d00b2 · Browse files · 16 files+104 added−175 removed
This commit

State

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

Diff stats

16 files+104 added−175 removed

  • tests:+10 added−54 removed
  • other:+94 added−121 removed

16 files+104 added−175 removed

modified:docs/advanced.md+1 added-15 removed
139 unmodified lines
140>>> r141<Response [200 OK]>142```143144## Specify the version of the HTTP protocol145146One can set the version of the HTTP protocol for the client in case you want to make the requests using a specific version.147148For example:149150```python151async with httpx.Client(http_versions=["HTTP/1.1"]) as h11_client:152 h11_response = await h11_client.get("https://myserver.com")153154async with httpx.Client(http_versions=["HTTP/2"]) as h2_client:155 h2_response = await h2_client.get("https://myserver.com")156```157144## .netrc Support145146HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is147not defined, HTTPX tries to add auth into request's header from .netrc file.
204 unmodified lines
352353- The first element is an optional file name which can be set to `None`.354- The second element may be a file-like object or a string which will be automatically355encoded in UTF-8.370- An optional third element can be used to specify the 356- An optional third element can be used to specify the357[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)358of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based359on the file name, with unknown file extensions defaulting to "application/octet-stream".360If the file name is explicitly set to `None` then HTTPX will not include a content-type
75 unmodified lines
added:docs/http2.md+60 added
modified:docs/index.md+3 added-2 removed
modified:httpx/dispatch/connection_pool.py+3 added-4 removed
4 unmodified lines
5from ..config import (6 DEFAULT_POOL_LIMITS,7 DEFAULT_TIMEOUT_CONFIG,8 CertTypes,9 HTTPVersionTypes,9 PoolLimits,10 TimeoutConfig,11 TimeoutTypes,12 VerifyTypes,
73 unmodified lines
86 cert: CertTypes = None,87 trust_env: bool = None,88 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,89 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,91 http_versions: HTTPVersionTypes = None,90 http_2: bool = False,91 backend: ConcurrencyBackend = None,92 uds: typing.Optional[str] = None,93 ):94 self.verify = verify95 self.cert = cert96 self.timeout = TimeoutConfig(timeout)97 self.pool_limits = pool_limits99 self.http_versions = http_versions98 self.http_2 = http_299 self.is_closed = False100 self.trust_env = trust_env101 self.uds = uds102
45 unmodified lines
148 origin,149 verify=self.verify,150 cert=self.cert,151 timeout=self.timeout,153 http_versions=self.http_versions,152 http_2=self.http_2,153 backend=self.backend,154 release_func=self.release_connection,155 trust_env=self.trust_env,156 uds=self.uds,
42 unmodified lines
modified:httpx/dispatch/connection.py+3 added-7 removed
5 unmodified lines
6from ..concurrency.base import ConcurrencyBackend7from ..config import (8 DEFAULT_TIMEOUT_CONFIG,9 CertTypes,10 HTTPVersionConfig,11 HTTPVersionTypes,10 SSLConfig,11 TimeoutConfig,12 TimeoutTypes,13 VerifyTypes,
18 unmodified lines
32 verify: VerifyTypes = True,33 cert: CertTypes = None,34 trust_env: bool = None,35 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,38 http_versions: HTTPVersionTypes = None,36 http_2: bool = False,37 backend: ConcurrencyBackend = None,38 release_func: typing.Optional[ReleaseCallback] = None,39 uds: typing.Optional[str] = None,40 ):41 self.origin = Origin(origin) if isinstance(origin, str) else origin42 self.ssl = SSLConfig(cert=cert, verify=verify, trust_env=trust_env)43 self.timeout = TimeoutConfig(timeout)46 self.http_versions = HTTPVersionConfig(http_versions)44 self.http_2 = http_245 self.backend = AsyncioBackend() if backend is None else backend46 self.release_func = release_func47 self.uds = uds48 self.h11_connection = None # type: typing.Optional[HTTP11Connection]
67 unmodified lines
116 if not self.origin.is_ssl:117 return None118119 # Run the SSL loading in a threadpool, since it may make disk accesses.122 return await self.backend.run_in_threadpool(123 ssl.load_ssl_context, self.http_versions124 )120 return await self.backend.run_in_threadpool(ssl.load_ssl_context, self.http_2)121122 async def close(self) -> None:123 logger.trace("close_connection")124 if self.h2_connection is not None:
26 unmodified lines
modified:httpx/dispatch/proxy_http.py+3 added-4 removed
6 unmodified lines
7from ..config import (8 DEFAULT_POOL_LIMITS,9 DEFAULT_TIMEOUT_CONFIG,10 CertTypes,11 HTTPVersionTypes,11 PoolLimits,12 SSLConfig,13 TimeoutTypes,14 VerifyTypes,
30 unmodified lines
45 cert: CertTypes = None,46 trust_env: bool = None,47 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,48 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,50 http_versions: HTTPVersionTypes = None,49 http_2: bool = False,50 backend: ConcurrencyBackend = None,51 ):5253 super(HTTPProxy, self).__init__(
2 unmodified lines
56 timeout=timeout,57 pool_limits=pool_limits,58 backend=backend,59 trust_env=trust_env,61 http_versions=http_versions,60 http_2=http_2,61 )6263 self.proxy_url = URL(proxy_url)64 self.proxy_mode = proxy_mode
67 unmodified lines
132 verify=self.verify,133 cert=self.cert,134 timeout=self.timeout,135 backend=self.backend,137 http_versions=["HTTP/1.1"], # Short-lived 'connection'136 http_2=False, # Short-lived 'connection'137 trust_env=self.trust_env,138 release_func=self.release_connection,139 )140 self.active_connections.add(connection)
111 unmodified lines
modified:httpx/__init__.py-4 removed
10 unmodified lines
11)12from .config import (13 USER_AGENT,14 CertTypes,15 HTTPVersionConfig,16 HTTPVersionTypes,15 PoolLimits,16 SSLConfig,17 TimeoutConfig,18 TimeoutTypes,
96 unmodified lines
115 "URLTypes",116 "StatusCode",117 "codes",118 "TimeoutTypes",121 "HTTPVersionTypes",122 "HTTPVersionConfig",119 "AuthTypes",120 "Cookies",121 "CookieTypes",122 "Headers",
11 unmodified lines
modified:httpx/api.py+1 added-5 removed
79 unmodified lines
80 <Response [200 OK]>81 ```82 """83 async with Client(84 http_versions=["HTTP/1.1"],85 cert=cert,86 verify=verify,87 timeout=timeout,88 trust_env=trust_env,84 cert=cert, verify=verify, timeout=timeout, trust_env=trust_env,85 ) as client:86 return await client.request(87 method=method,88 url=url,
287 unmodified lines
modified:httpx/client.py+8 added-9 removed
10 unmodified lines
11 DEFAULT_MAX_REDIRECTS,12 DEFAULT_POOL_LIMITS,13 DEFAULT_TIMEOUT_CONFIG,14 CertTypes,15 HTTPVersionTypes,15 PoolLimits,16 TimeoutTypes,17 VerifyTypes,18)
58 unmodified lines
77 * **cert** - *(optional)* An SSL certificate used by the requested host78 to authenticate the client. Either a path to an SSL certificate file, or79 two-tuple of (certificate file, key file), or a three-tuple of (certificate80 file, key file, password).82 * **http_versions** - *(optional)* A list of strings of HTTP protocol83 versions to use when sending requests. eg. `http_versions=["HTTP/1.1"]`81 * **http_2** - *(optional)* A boolean indicating if HTTP/2 support should be82 enabled. Defaults to `False`.83 * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy84 URLs.85 * **timeout** - *(optional)* The timeout configuration to use when sending86 requests.
22 unmodified lines
109 headers: HeaderTypes = None,110 cookies: CookieTypes = None,111 verify: VerifyTypes = True,112 cert: CertTypes = None,114 http_versions: HTTPVersionTypes = None,113 http_2: bool = False,114 proxies: ProxiesTypes = None,115 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,116 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,117 max_redirects: int = DEFAULT_MAX_REDIRECTS,
14 unmodified lines
132 dispatch = ConnectionPool(133 verify=verify,134 cert=cert,135 timeout=timeout,137 http_versions=http_versions,136 http_2=http_2,137 pool_limits=pool_limits,138 backend=backend,139 trust_env=trust_env,140 uds=uds,
24 unmodified lines
165 proxies,166 verify=verify,167 cert=cert,168 timeout=timeout,170 http_versions=http_versions,169 http_2=http_2,170 pool_limits=pool_limits,171 backend=backend,172 trust_env=trust_env,173 )
657 unmodified lines
831 proxies: typing.Optional[ProxiesTypes],832 verify: VerifyTypes,833 cert: typing.Optional[CertTypes],834 timeout: TimeoutTypes,836 http_versions: typing.Optional[HTTPVersionTypes],835 http_2: bool,836 pool_limits: PoolLimits,837 backend: ConcurrencyBackend,838 trust_env: bool,839) -> typing.Dict[str, Dispatcher]:840 def _proxy_from_url(url: URLTypes) -> Dispatcher:842 nonlocal verify, cert, timeout, http_versions, pool_limits, backend, trust_env841 nonlocal verify, cert, timeout, http_2, pool_limits, backend, trust_env842 url = URL(url)843 if url.scheme in ("http", "https"):844 return HTTPProxy(845 url,
2 unmodified lines
848 timeout=timeout,849 pool_limits=pool_limits,850 backend=backend,851 trust_env=trust_env,853 http_versions=http_versions,852 http_2=http_2,853 )854 raise ValueError(f"Unknown proxy for {url!r}")855856 if proxies is None:
13 unmodified lines
modified:httpx/config.py+11 added-71 removed
11 unmodified lines
12VerifyTypes = typing.Union[str, bool, ssl.SSLContext]13TimeoutTypes = typing.Union[14 float, typing.Tuple[float, float, float, float], "TimeoutConfig"15]16HTTPVersionTypes = typing.Union[17 str, typing.List[str], typing.Tuple[str], "HTTPVersionConfig"18]161718USER_AGENT = f"python-httpx/{__version__}"1923HTTP_VERSIONS_TO_ALPN_IDENTIFIERS = {"HTTP/1.1": "http/1.1", "HTTP/2": "h2"}2420DEFAULT_CIPHERS = ":".join(21 [22 "ECDHE+AESGCM",23 "ECDHE+CHACHA20",
61 unmodified lines
85 if (cert == self.cert) and (verify == self.verify):86 return self87 return SSLConfig(cert=cert, verify=verify)8894 def load_ssl_context(95 self, http_versions: "HTTPVersionConfig" = None96 ) -> ssl.SSLContext:97 http_versions = HTTPVersionConfig() if http_versions is None else http_versions9889 def load_ssl_context(self, http_2: bool = False) -> ssl.SSLContext:90 logger.trace(91 f"load_ssl_context "92 f"verify={self.verify!r} "93 f"cert={self.cert!r} "94 f"trust_env={self.trust_env!r} "104 f"http_versions={http_versions!r}"95 f"http_2={http_2!r}"96 )9798 if self.ssl_context is None:99 self.ssl_context = (109 self.load_ssl_context_verify(http_versions=http_versions)100 self.load_ssl_context_verify(http_2=http_2)101 if self.verify111 else self.load_ssl_context_no_verify(http_versions=http_versions)102 else self.load_ssl_context_no_verify(http_2=http_2)103 )104105 assert self.ssl_context is not None106 return self.ssl_context107117 def load_ssl_context_no_verify(118 self, http_versions: "HTTPVersionConfig"119 ) -> ssl.SSLContext:108 def load_ssl_context_no_verify(self, http_2: bool = False) -> ssl.SSLContext:109 """110 Return an SSL context for unverified connections.111 """123 context = self._create_default_ssl_context(http_versions=http_versions)112 context = self._create_default_ssl_context(http_2=http_2)113 context.verify_mode = ssl.CERT_NONE114 context.check_hostname = False115 return context116128 def load_ssl_context_verify(129 self, http_versions: "HTTPVersionConfig"130 ) -> ssl.SSLContext:117 def load_ssl_context_verify(self, http_2: bool = False) -> ssl.SSLContext:118 """119 Return an SSL context for verified connections.120 """121 if self.trust_env and self.verify is True:
10 unmodified lines
132 "Could not find a suitable TLS CA certificate bundle, "133 "invalid path: {}".format(self.verify)134 )135149 context = self._create_default_ssl_context(http_versions=http_versions)136 context = self._create_default_ssl_context(http_2=http_2)137 context.verify_mode = ssl.CERT_REQUIRED138 context.check_hostname = True139140 # Signal to server support for PHA in TLS 1.3. Raises an
20 unmodified lines
161 self._load_client_certs(context)162163 return context164178 def _create_default_ssl_context(179 self, http_versions: "HTTPVersionConfig"180 ) -> ssl.SSLContext:165 def _create_default_ssl_context(self, http_2: bool) -> ssl.SSLContext:166 """167 Creates the default SSLContext object that's used for both verified168 and unverified connections.169 """
5 unmodified lines
175 context.options |= ssl.OP_NO_COMPRESSION176 context.set_ciphers(DEFAULT_CIPHERS)177178 if ssl.HAS_ALPN:194 context.set_alpn_protocols(http_versions.alpn_identifiers)179 alpn_idents = ["http/1.1", "h2"] if http_2 else ["http/1.1"]180 context.set_alpn_protocols(alpn_idents)181182 if hasattr(context, "keylog_filename"):183 keylogfile = os.environ.get("SSLKEYLOGFILE")184 if keylogfile and self.trust_env:
88 unmodified lines
273 f"pool_timeout={self.pool_timeout})"274 )275276291class HTTPVersionConfig:292 """293 Configure which HTTP protocol versions are supported.294 """295296 def __init__(self, http_versions: HTTPVersionTypes = None):297 if http_versions is None:298 http_versions = ["HTTP/1.1", "HTTP/2"]299300 if isinstance(http_versions, str):301 self.http_versions = {http_versions.upper()}302 elif isinstance(http_versions, HTTPVersionConfig):303 self.http_versions = http_versions.http_versions304 elif isinstance(http_versions, typing.Iterable):305 self.http_versions = {306 version.upper() if isinstance(version, str) else version307 for version in http_versions308 }309 else:310 raise TypeError(311 "HTTP version should be a string or list of strings, "312 f"but got {type(http_versions)}"313 )314315 for version in self.http_versions:316 if version not in ("HTTP/1.1", "HTTP/2"):317 raise ValueError(f"Unsupported HTTP version {version!r}.")318319 if not self.http_versions:320 raise ValueError("HTTP versions cannot be an empty list.")321322 @property323 def alpn_identifiers(self) -> typing.List[str]:324 """325 Returns a list of supported ALPN identifiers. (One or more of "http/1.1", "h2").326 """327 return [328 HTTP_VERSIONS_TO_ALPN_IDENTIFIERS[version] for version in self.http_versions329 ]330331 def __repr__(self) -> str:332 class_name = self.__class__.__name__333 value = sorted(list(self.http_versions))334 return f"{class_name}({value!r})"335336277class PoolLimits:278 """279 Limits on the number of connections in a connection pool.280 """
26 unmodified lines
modified:tests/client/test_proxies.py-2 removed
34 unmodified lines
35 verify="/path/to/verify",36 cert="/path/to/cert",37 trust_env=False,38 timeout=30,39 http_versions=["HTTP/1.1"],39 )40 pool = client.dispatch41 proxy = client.proxies["all"]42
4 unmodified lines
47 "verify",48 "cert",49 "timeout",50 "pool_limits",52 "http_versions",51 "backend",52 ]:53 assert getattr(pool, prop) == getattr(proxy, prop)54
61 unmodified lines
modified:tests/dispatch/test_http2.py+7 added-7 removed
25 unmodified lines
26@pytest.mark.asyncio27async def test_http2_get_request():28 backend = MockHTTP2Backend(app=app)2930 async with Client(backend=backend) as client:30 async with Client(backend=backend, http_2=True) as client:31 response = await client.get("http://example.org")3233 assert response.status_code == 20034 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}
2 unmodified lines
37@pytest.mark.asyncio38async def test_http2_post_request():39 backend = MockHTTP2Backend(app=app)4041 async with Client(backend=backend) as client:41 async with Client(backend=backend, http_2=True) as client:42 response = await client.post("http://example.org", data=b"<data>")4344 assert response.status_code == 20045 assert json.loads(response.content) == {
7 unmodified lines
53async def test_http2_large_post_request():54 backend = MockHTTP2Backend(app=app)5556 data = b"a" * 10000057 async with Client(backend=backend) as client:57 async with Client(backend=backend, http_2=True) as client:58 response = await client.post("http://example.org", data=data)59 assert response.status_code == 20060 assert json.loads(response.content) == {61 "method": "POST",
5 unmodified lines
67@pytest.mark.asyncio68async def test_http2_multiple_requests():69 backend = MockHTTP2Backend(app=app)7071 async with Client(backend=backend) as client:71 async with Client(backend=backend, http_2=True) as client:72 response_1 = await client.get("http://example.org/1")73 response_2 = await client.get("http://example.org/2")74 response_3 = await client.get("http://example.org/3")75
14 unmodified lines
90 be seemlessly reconnected.91 """92 backend = MockHTTP2Backend(app=app)9394 async with Client(backend=backend) as client:94 async with Client(backend=backend, http_2=True) as client:95 response_1 = await client.get("http://example.org/1")96 backend.server.close_connection = True97 response_2 = await client.get("http://example.org/2")98
6 unmodified lines
105106async def test_http2_settings_in_handshake(backend):107 backend = MockHTTP2Backend(app=app, backend=backend)108109 async with Client(backend=backend) as client:109 async with Client(backend=backend, http_2=True) as client:110 await client.get("http://example.org")111112 h2_conn = backend.server.conn113
24 unmodified lines
138 assert changed_setting.new_value == expected_settings[setting_code]139140141async def test_http2_live_request(backend):142 async with Client(backend=backend) as client:142 async with Client(backend=backend, http_2=True) as client:143 try:144 resp = await client.get("https://nghttp2.org/httpbin/anything")145 except Timeout:146 pytest.xfail(reason="nghttp2.org appears to be unresponsive")
4 unmodified lines
modified:tests/test_concurrency.py+3 added-3 removed
1import pytest2import trio34from httpx import AsyncioBackend, HTTPVersionConfig, SSLConfig, TimeoutConfig4from httpx import AsyncioBackend, SSLConfig, TimeoutConfig5from httpx.concurrency.trio import TrioBackend6from tests.concurrency import run_concurrently78
30 unmodified lines
39 pytest.param(TrioBackend(), get_trio_cipher, marks=pytest.mark.trio),40 ],41)42async def test_start_tls_on_tcp_socket_stream(https_server, backend, get_cipher):43 ctx = SSLConfig().load_ssl_context_no_verify(HTTPVersionConfig())43 ctx = SSLConfig().load_ssl_context_no_verify()44 timeout = TimeoutConfig(5)4546 stream = await backend.open_tcp_stream(47 https_server.url.host, https_server.url.port, None, timeout
23 unmodified lines
71 pytest.param(TrioBackend(), get_trio_cipher, marks=pytest.mark.trio),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(HTTPVersionConfig())75 ctx = SSLConfig().load_ssl_context_no_verify()76 timeout = TimeoutConfig(5)7778 stream = await backend.open_uds_stream(79 https_uds_server.config.uds, https_uds_server.url.host, None, timeout
33 unmodified lines
modified:tests/test_config.py-40 removed
116 unmodified lines
117 ssl = httpx.SSLConfig(verify=False)118 assert repr(ssl) == "SSLConfig(cert=None, verify=False)"119120121def test_http_versions_repr():122 http_versions = httpx.HTTPVersionConfig()123 assert repr(http_versions) == "HTTPVersionConfig(['HTTP/1.1', 'HTTP/2'])"124125126def test_http_versions_from_string():127 http_versions = httpx.HTTPVersionConfig("HTTP/1.1")128 assert repr(http_versions) == "HTTPVersionConfig(['HTTP/1.1'])"129130131def test_http_versions_from_list():132 http_versions = httpx.HTTPVersionConfig(["http/1.1"])133 assert repr(http_versions) == "HTTPVersionConfig(['HTTP/1.1'])"134135136def test_http_versions_from_config():137 http_versions = httpx.HTTPVersionConfig(httpx.HTTPVersionConfig("HTTP/1.1"))138 assert repr(http_versions) == "HTTPVersionConfig(['HTTP/1.1'])"139140141def test_invalid_http_version():142 with pytest.raises(ValueError):143 httpx.HTTPVersionConfig("HTTP/9")144145146def test_invalid_http_version_type():147 with pytest.raises(TypeError):148 httpx.HTTPVersionConfig(123)149150151def test_invalid_http_version_list_type():152 with pytest.raises(ValueError):153 httpx.HTTPVersionConfig([123])154155156def test_empty_http_version():157 with pytest.raises(ValueError):158 httpx.HTTPVersionConfig([])159160121def test_limits_repr():122 limits = httpx.PoolLimits(hard_limit=100)123 assert repr(limits) == "PoolLimits(soft_limit=None, hard_limit=100)"124
83 unmodified lines
modified:tests/test_multipart.py-2 removed
8 unmodified lines
9from httpx import (10 CertTypes,11 Client,12 Dispatcher,13 HTTPVersionTypes,13 Request,14 Response,15 TimeoutTypes,16 VerifyTypes,
7 unmodified lines
24 request: Request,25 verify: VerifyTypes = None,26 cert: CertTypes = None,27 timeout: TimeoutTypes = None,29 http_versions: HTTPVersionTypes = None,28 ) -> Response:29 content = await request.read()30 return Response(200, content=content)31
175 unmodified lines
modified:mkdocs.yml+1 added
10 unmodified lines
11nav:12 - Introduction: 'index.md'13 - QuickStart: 'quickstart.md'14 - Advanced Usage: 'advanced.md'15 - HTTP/2 Support: 'http2.md'16 - Environment Variables: 'environment_variables.md'17 - Requests Compatibility: 'compatibility.md'18 - Developer Interface: 'api.md'19 - Contributing: 'contributing.md'
8 unmodified lines