Rename http2 switch (#586)
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 * Add concurrency auto-detection * Add sniffio * Rename HTTP2 switch on client * http_2 -> http2
authored by Tom Christie · committed by GitHub · parent 3cbe731 · Browse files · 7 files·+36 added−36 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+36 added−36 removed
- tests:+7 added−7 removed
- other:+29 added−29 removed
Provenance
- Commit
5076952- Tree
6f00e22- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
3cbe731
7 files changed+36 added−36 removed
modified:docs/http2.md+3 added-3 removed
28 unmodified lines29303132333334353637383940414242434445466 unmodified lines53545556575758596028 unmodified linestrying out our HTTP/2 support. You can do so by instantiating a client withHTTP/2 support enabled:
```pythonclient = httpx.Client(http_2=True)client = httpx.Client(http2=True)...```
You can also instantiate a client as a context manager, to ensure that allHTTP connections are nicely scoped, and will be closed once the context blockis exited.
```pythonasync with httpx.Client(http_2=True) as client:async with httpx.Client(http2=True) as client: ...```
## Inspecting the HTTP version6 unmodified linesYou can determine which version of the HTTP protocol was used by examiningthe `.http_version` property on the response.
```pythonclient = httpx.Client(http_2=True)client = httpx.Client(http2=True)response = await client.get(...)print(response.http_version) # "HTTP/1.0", "HTTP/1.1", or "HTTP/2".```modified:httpx/dispatch/connection_pool.py+3 added-3 removed
84 unmodified lines85 cert: CertTypes = None,86 trust_env: bool = None,87 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,88 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,89- http_2: bool = False,89+ http2: bool = False,90 backend: typing.Union[str, ConcurrencyBackend] = "auto",91 uds: typing.Optional[str] = None,92 ):93 self.verify = verify94 self.cert = cert95 self.timeout = TimeoutConfig(timeout)96 self.pool_limits = pool_limits97- self.http_2 = http_297+ self.http2 = http298 self.is_closed = False99 self.trust_env = trust_env100 self.uds = uds101 52 unmodified lines154 origin,155 verify=self.verify,156 cert=self.cert,157 timeout=self.timeout,158- http_2=self.http_2,158+ http2=self.http2,159 backend=self.backend,160 release_func=self.release_connection,161 trust_env=self.trust_env,162 uds=self.uds,42 unmodified linesmodified:httpx/dispatch/connection.py+3 added-3 removed
30 unmodified lines31 verify: VerifyTypes = True,32 cert: CertTypes = None,33 trust_env: bool = None,34 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,35- http_2: bool = False,35+ http2: bool = False,36 backend: typing.Union[str, ConcurrencyBackend] = "auto",37 release_func: typing.Optional[ReleaseCallback] = None,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)43- self.http_2 = http_243+ self.http2 = http244 self.backend = lookup_backend(backend)45 self.release_func = release_func46 self.uds = uds47 self.h11_connection = None # type: typing.Optional[HTTP11Connection]65 unmodified lines113 if not self.origin.is_ssl:114 return None115 116 # Run the SSL loading in a threadpool, since it may make disk accesses.117- return await self.backend.run_in_threadpool(ssl.load_ssl_context, self.http_2)117+ return await self.backend.run_in_threadpool(ssl.load_ssl_context, self.http2)118 119 async def close(self) -> None:120 logger.trace("close_connection")121 if self.h2_connection is not None:26 unmodified linesmodified:httpx/dispatch/proxy_http.py+3 added-3 removed
45 unmodified lines46 cert: CertTypes = None,47 trust_env: bool = None,48 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,49 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,50- http_2: bool = False,50+ http2: bool = False,51 backend: typing.Union[str, ConcurrencyBackend] = "auto",52 ):53 54 super(HTTPProxy, self).__init__(2 unmodified lines57 timeout=timeout,58 pool_limits=pool_limits,59 backend=backend,60 trust_env=trust_env,61- http_2=http_2,61+ http2=http2,62 )63 64 self.proxy_url = URL(proxy_url)65 self.proxy_mode = proxy_mode67 unmodified lines133 verify=self.verify,134 cert=self.cert,135 timeout=self.timeout,136 backend=self.backend,137- http_2=False, # Short-lived 'connection'137+ http2=False, # Short-lived 'connection'138 trust_env=self.trust_env,139 release_func=self.release_connection,140 )141 self.active_connections.add(connection)109 unmodified linesmodified:httpx/client.py+7 added-7 removed
75 unmodified lines76 * **cert** - *(optional)* An SSL certificate used by the requested host77 to authenticate the client. Either a path to an SSL certificate file, or78 two-tuple of (certificate file, key file), or a three-tuple of (certificate79 file, key file, password).80- * **http_2** - *(optional)* A boolean indicating if HTTP/2 support should be80+ * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be81 enabled. Defaults to `False`.82 * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy83 URLs.84 * **timeout** - *(optional)* The timeout configuration to use when sending24 unmodified lines109 headers: HeaderTypes = None,110 cookies: CookieTypes = None,111 verify: VerifyTypes = True,112 cert: CertTypes = None,113- http_2: bool = False,113+ http2: 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,11 unmodified lines129 dispatch = ConnectionPool(130 verify=verify,131 cert=cert,132 timeout=timeout,133- http_2=http_2,133+ http2=http2,134 pool_limits=pool_limits,135 backend=backend,136 trust_env=trust_env,137 uds=uds,23 unmodified lines161 proxies,162 verify=verify,163 cert=cert,164 timeout=timeout,165- http_2=http_2,165+ http2=http2,166 pool_limits=pool_limits,167 backend=backend,168 trust_env=trust_env,169 )657 unmodified lines827 proxies: typing.Optional[ProxiesTypes],828 verify: VerifyTypes,829 cert: typing.Optional[CertTypes],830 timeout: TimeoutTypes,831- http_2: bool,831+ http2: bool,832 pool_limits: PoolLimits,833 backend: typing.Union[str, ConcurrencyBackend],834 trust_env: bool,835 ) -> typing.Dict[str, Dispatcher]:836 def _proxy_from_url(url: URLTypes) -> Dispatcher:837- nonlocal verify, cert, timeout, http_2, pool_limits, backend, trust_env837+ nonlocal verify, cert, timeout, http2, pool_limits, backend, trust_env838 url = URL(url)839 if url.scheme in ("http", "https"):840 return HTTPProxy(841 url,2 unmodified lines844 timeout=timeout,845 pool_limits=pool_limits,846 backend=backend,847 trust_env=trust_env,848- http_2=http_2,848+ http2=http2,849 )850 raise ValueError(f"Unknown proxy for {url!r}")851 852 if proxies is None:13 unmodified linesmodified:httpx/config.py+10 added-10 removed
84 unmodified lines85 if (cert == self.cert) and (verify == self.verify):86 return self87 return SSLConfig(cert=cert, verify=verify)88 89- def load_ssl_context(self, http_2: bool = False) -> ssl.SSLContext:89+ def load_ssl_context(self, http2: 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} "95- f"http_2={http_2!r}"95+ f"http2={http2!r}"96 )97 98 if self.ssl_context is None:99 self.ssl_context = (100- self.load_ssl_context_verify(http_2=http_2)100+ self.load_ssl_context_verify(http2=http2)101 if self.verify102- else self.load_ssl_context_no_verify(http_2=http_2)102+ else self.load_ssl_context_no_verify(http2=http2)103 )104 105 assert self.ssl_context is not None106 return self.ssl_context107 108- def load_ssl_context_no_verify(self, http_2: bool = False) -> ssl.SSLContext:108+ def load_ssl_context_no_verify(self, http2: bool = False) -> ssl.SSLContext:109 """110 Return an SSL context for unverified connections.111 """112- context = self._create_default_ssl_context(http_2=http_2)112+ context = self._create_default_ssl_context(http2=http2)113 context.verify_mode = ssl.CERT_NONE114 context.check_hostname = False115 return context116 117- def load_ssl_context_verify(self, http_2: bool = False) -> ssl.SSLContext:117+ def load_ssl_context_verify(self, http2: 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 lines132 "Could not find a suitable TLS CA certificate bundle, "133 "invalid path: {}".format(self.verify)134 )135 136- context = self._create_default_ssl_context(http_2=http_2)136+ context = self._create_default_ssl_context(http2=http2)137 context.verify_mode = ssl.CERT_REQUIRED138 context.check_hostname = True139 140 # Signal to server support for PHA in TLS 1.3. Raises an20 unmodified lines161 self._load_client_certs(context)162 163 return context164 165- def _create_default_ssl_context(self, http_2: bool) -> ssl.SSLContext:165+ def _create_default_ssl_context(self, http2: bool) -> ssl.SSLContext:166 """167 Creates the default SSLContext object that's used for both verified168 and unverified connections.169 """5 unmodified lines175 context.options |= ssl.OP_NO_COMPRESSION176 context.set_ciphers(DEFAULT_CIPHERS)177 178 if ssl.HAS_ALPN:179- alpn_idents = ["http/1.1", "h2"] if http_2 else ["http/1.1"]179+ alpn_idents = ["http/1.1", "h2"] if http2 else ["http/1.1"]180 context.set_alpn_protocols(alpn_idents)181 182 if hasattr(context, "keylog_filename"):183 keylogfile = os.environ.get("SSLKEYLOGFILE")123 unmodified linesmodified:tests/dispatch/test_http2.py+7 added-7 removed
25 unmodified lines26 @pytest.mark.asyncio27 async def test_http2_get_request():28 backend = MockHTTP2Backend(app=app)29 30- async with Client(backend=backend, http_2=True) as client:30+ async with Client(backend=backend, http2=True) as client:31 response = await client.get("http://example.org")32 33 assert response.status_code == 20034 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}2 unmodified lines37 @pytest.mark.asyncio38 async def test_http2_post_request():39 backend = MockHTTP2Backend(app=app)40 41- async with Client(backend=backend, http_2=True) as client:41+ async with Client(backend=backend, http2=True) as client:42 response = await client.post("http://example.org", data=b"<data>")43 44 assert response.status_code == 20045 assert json.loads(response.content) == {7 unmodified lines53 async def test_http2_large_post_request():54 backend = MockHTTP2Backend(app=app)55 56 data = b"a" * 10000057- async with Client(backend=backend, http_2=True) as client:57+ async with Client(backend=backend, http2=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 lines67 @pytest.mark.asyncio68 async def test_http2_multiple_requests():69 backend = MockHTTP2Backend(app=app)70 71- async with Client(backend=backend, http_2=True) as client:71+ async with Client(backend=backend, http2=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 lines90 be seemlessly reconnected.91 """92 backend = MockHTTP2Backend(app=app)93 94- async with Client(backend=backend, http_2=True) as client:94+ async with Client(backend=backend, http2=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 lines105 106 async def test_http2_settings_in_handshake(backend):107 backend = MockHTTP2Backend(app=app, backend=backend)108 109- async with Client(backend=backend, http_2=True) as client:109+ async with Client(backend=backend, http2=True) as client:110 await client.get("http://example.org")111 112 h2_conn = backend.server.conn113 24 unmodified lines138 assert changed_setting.new_value == expected_settings[setting_code]139 140 141 async def test_http2_live_request(backend):142- async with Client(backend=backend, http_2=True) as client:142+ async with Client(backend=backend, http2=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