Skip to content
Myr

Drop backend parameter on AsyncClient (#791)

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

* Drop backend parameter on AsyncClient * Fix master merge

authored by Florimond Manca · committed by GitHub · parent 2714f32 · Browse files · 5 files+19 added−39 removed
This commit

State

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

Trailers

  • Co-authored-by: Tom Christie <tom@tomchristie.com>

Diff stats

5 files+19 added−39 removed

  • tests:+18 added−18 removed
  • other:+1 added−21 removed

5 files+19 added−39 removed

modified:docs/async.md+1 added-10 removed
93 unmodified lines
94## Supported async environments9596HTTPX supports either `asyncio` or `trio` as an async environment.9798By default it will auto-detect which of those two to use as the backend98It will auto-detect which of those two to use as the backend99for socket operations and concurrency primitives.100101You can also explicitly select a backend by instantiating a client with the102`backend` argument...103104```python105client = httpx.AsyncClient(backend='auto') # Autodetection. The default case.106client = httpx.AsyncClient(backend='asyncio') # Use asyncio as the backend.107client = httpx.AsyncClient(backend='trio') # Use trio as the backend.108```109101### [AsyncIO](https://docs.python.org/3/library/asyncio.html)102103AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)104for writing concurrent code with the async/await syntax.
97 unmodified lines
modified:httpx/_client.py-11 removed
3 unmodified lines
45import hstspreload67from ._auth import Auth, AuthTypes, BasicAuth, FunctionAuth8from ._backends.base import ConcurrencyBackend8from ._config import (9 DEFAULT_MAX_REDIRECTS,10 DEFAULT_POOL_LIMITS,11 DEFAULT_TIMEOUT_CONFIG,
908 unmodified lines
920 * **dispatch** - *(optional)* A dispatch class to use for sending requests921 over the network.922 * **app** - *(optional)* An ASGI application to send requests to,923 rather than sending actual network requests.925 * **backend** - *(optional)* A concurrency backend to use when issuing926 async requests. Either 'auto', 'asyncio', 'trio', or a `ConcurrencyBackend`927 instance. Defaults to 'auto', for autodetection.924 * **trust_env** - *(optional)* Enables or disables usage of environment925 variables for configuration.926 * **uds** - *(optional)* A path to a Unix domain socket to connect through.927 """
14 unmodified lines
942 max_redirects: int = DEFAULT_MAX_REDIRECTS,943 base_url: URLTypes = None,944 dispatch: AsyncDispatcher = None,945 app: typing.Callable = None,950 backend: typing.Union[str, ConcurrencyBackend] = "auto",946 trust_env: bool = True,947 uds: str = None,948 ):949 super().__init__(
15 unmodified lines
965 http2=http2,966 pool_limits=pool_limits,967 dispatch=dispatch,968 app=app,974 backend=backend,969 trust_env=trust_env,970 uds=uds,971 )972 self.proxies: typing.Dict[str, AsyncDispatcher] = {
2 unmodified lines
975 verify=verify,976 cert=cert,977 http2=http2,978 pool_limits=pool_limits,985 backend=backend,979 trust_env=trust_env,980 )981 for key, proxy in proxy_map.items()982 }
5 unmodified lines
988 http2: bool = False,989 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,990 dispatch: AsyncDispatcher = None,991 app: typing.Callable = None,999 backend: typing.Union[str, ConcurrencyBackend] = "auto",992 trust_env: bool = True,993 uds: str = None,994 ) -> AsyncDispatcher:995 if dispatch is not None:
6 unmodified lines
1002 verify=verify,1003 cert=cert,1004 http2=http2,1005 pool_limits=pool_limits,1014 backend=backend,1006 trust_env=trust_env,1007 uds=uds,1008 )1009
3 unmodified lines
1013 verify: VerifyTypes = True,1014 cert: CertTypes = None,1015 http2: bool = False,1016 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,1026 backend: typing.Union[str, ConcurrencyBackend] = "auto",1017 trust_env: bool = True,1018 ) -> AsyncDispatcher:1019 return HTTPProxy(1020 proxy_url=proxy.url,
2 unmodified lines
1023 verify=verify,1024 cert=cert,1025 http2=http2,1026 pool_limits=pool_limits,1037 backend=backend,1027 trust_env=trust_env,1028 )10291030 def dispatcher_for_url(self, url: URL) -> AsyncDispatcher:
427 unmodified lines
modified:tests/client/test_async_client.py-7 removed
158 unmodified lines
159 response = await client.get(url)160 assert response.status_code == 200161 assert response.text == "Hello, world!"162 assert response.encoding == "iso-8859-1"163164165async def test_explicit_backend(server, async_environment):166 async with httpx.AsyncClient(backend=async_environment) as client:167 response = await client.get(server.url)168 assert response.status_code == 200169 assert response.text == "Hello, world!"
modified:tests/dispatch/test_http2.py+13 added-6 removed
5 unmodified lines
6import pytest7from h2.settings import SettingCodes89from httpx import AsyncClient, Response, TimeoutException10from httpx._dispatch.connection_pool import ConnectionPool1112from .utils import MockHTTP2Backend1314
10 unmodified lines
2526@pytest.mark.asyncio27async def test_http2_get_request():28 backend = MockHTTP2Backend(app=app)29 dispatch = ConnectionPool(backend=backend, http2=True)3029 async with AsyncClient(backend=backend, http2=True) as client:31 async with AsyncClient(dispatch=dispatch) as client:32 response = await client.get("http://example.org")3334 assert response.status_code == 20035 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}
1 unmodified line
3738@pytest.mark.asyncio39async def test_http2_post_request():40 backend = MockHTTP2Backend(app=app)41 dispatch = ConnectionPool(backend=backend, http2=True)4240 async with AsyncClient(backend=backend, http2=True) as client:43 async with AsyncClient(dispatch=dispatch) as client:44 response = await client.post("http://example.org", data=b"<data>")4546 assert response.status_code == 20047 assert json.loads(response.content) == {
5 unmodified lines
5354@pytest.mark.asyncio55async def test_http2_large_post_request():56 backend = MockHTTP2Backend(app=app)57 dispatch = ConnectionPool(backend=backend, http2=True)5859 data = b"a" * 10000056 async with AsyncClient(backend=backend, http2=True) as client:60 async with AsyncClient(dispatch=dispatch) as client:61 response = await client.post("http://example.org", data=data)62 assert response.status_code == 20063 assert json.loads(response.content) == {64 "method": "POST",
4 unmodified lines
6970@pytest.mark.asyncio71async def test_http2_multiple_requests():72 backend = MockHTTP2Backend(app=app)73 dispatch = ConnectionPool(backend=backend, http2=True)7470 async with AsyncClient(backend=backend, http2=True) as client:75 async with AsyncClient(dispatch=dispatch) as client:76 response_1 = await client.get("http://example.org/1")77 response_2 = await client.get("http://example.org/2")78 response_3 = await client.get("http://example.org/3")79
13 unmodified lines
93 If a connection has been dropped between requests, then we should94 be seemlessly reconnected.95 """96 backend = MockHTTP2Backend(app=app)97 dispatch = ConnectionPool(backend=backend, http2=True)9893 async with AsyncClient(backend=backend, http2=True) as client:99 async with AsyncClient(dispatch=dispatch) as client:100 response_1 = await client.get("http://example.org/1")101 backend.server.close_connection = True102 response_2 = await client.get("http://example.org/2")103
6 unmodified lines
110111@pytest.mark.asyncio112async def test_http2_settings_in_handshake():113 backend = MockHTTP2Backend(app=app)114 dispatch = ConnectionPool(backend=backend, http2=True)115109 async with AsyncClient(backend=backend, http2=True) as client:116 async with AsyncClient(dispatch=dispatch) as client:117 await client.get("http://example.org")118119 h2_conn = backend.server.conn120
38 unmodified lines
modified:tests/dispatch/utils.py+5 added-5 removed
8 unmodified lines
9from httpx._backends.base import BaseSocketStream, lookup_backend101112class MockHTTP2Backend:13 def __init__(self, app, backend="auto"):13 def __init__(self, app):14 self.app = app15 self.backend = lookup_backend(backend)15 self.backend = lookup_backend()16 self.server = None1718 async def open_tcp_stream(19 self,
10 unmodified lines
30 return getattr(self.backend, name)313233class MockHTTP2Server(BaseSocketStream):34 def __init__(self, app, backend):34 def __init__(self, app, backend: MockHTTP2Backend):35 config = h2.config.H2Configuration(client_side=False)36 self.conn = h2.connection.H2Connection(config=config)37 self.app = app38 self.backend = backend
111 unmodified lines
150 self.buffer += self.conn.data_to_send()151152153class MockRawSocketBackend:154 def __init__(self, data_to_send=b"", backend="auto"):155 self.backend = lookup_backend(backend)154 def __init__(self, data_to_send=b""):155 self.backend = lookup_backend()156 self.data_to_send = data_to_send157 self.received_data = []158 self.stream = MockRawSocketStream(self)159
45 unmodified lines