Skip to content
Myr

Deprecate `app=...` in favor of explicit `WSGITransport`/`ASGITransport`. (#3050)

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

* Deprecate app=... in favour of explicit WSGITransport/ASGITransport * Linting * Linting * Update WSGITransport and ASGITransport docs * Deprecate app * Drop deprecation tests * Add CHANGELOG * Deprecate 'app=...' shortcut, rather than removing it. * Update CHANGELOG * Fix test_asgi.test_deprecated_shortcut

authored by Tom Christie · committed by GitHub · parent 6f46152 · Browse files · 6 files+145 added−72 removed
This commit

State

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

Diff stats

6 files+145 added−72 removed

  • tests:+55 added−18 removed
  • other:+90 added−54 removed

6 files+145 added−72 removed

modified:docs/advanced/transports.md+70 added-2 removed
40 unmodified lines
4142This is particularly useful for two main use-cases:4344* Using `httpx` as a client inside test cases.45* Mocking out external services during tests or in dev/staging environments.45* Mocking out external services during tests or in dev or staging environments.4647### Example4849Here's an example of integrating against a Flask application:5051```python52from flask import Flask
5 unmodified lines
58@app.route("/")59def hello():60 return "Hello World!"6162transport = httpx.WSGITransport(app=app)60with httpx.Client(app=app, base_url="http://testserver") as client:63with httpx.Client(transport=transport, base_url="http://testserver") as client:64 r = client.get("/")65 assert r.status_code == 20066 assert r.text == "Hello World!"67```6869### Configuration7071For some more complex cases you might need to customize the WSGI transport. This allows you to:7273* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.74* Mount the WSGI application at a subpath by setting `script_name` (WSGI).
7 unmodified lines
82with httpx.Client(transport=transport, base_url="http://testserver") as client:83 ...84```8586## ASGITransport8788You can configure an `httpx` client to call directly into an async Python web application using the ASGI protocol.8990This is particularly useful for two main use-cases:9192* Using `httpx` as a client inside test cases.93* Mocking out external services during tests or in dev or staging environments.9495### Example9697Let's take this Starlette application as an example:9899```python100from starlette.applications import Starlette101from starlette.responses import HTMLResponse102from starlette.routing import Route103104105async def hello(request):106 return HTMLResponse("Hello World!")107108109app = Starlette(routes=[Route("/", hello)])110```111112We can make requests directly against the application, like so:113114```python115transport = httpx.ASGITransport(app=app)116117async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:118 r = await client.get("/")119 assert r.status_code == 200120 assert r.text == "Hello World!"121```122123### Configuration124125For some more complex cases you might need to customise the ASGI transport. This allows you to:126127* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.128* Mount the ASGI application at a subpath by setting `root_path`.129* Use a given client address for requests by setting `client`.130131For example:132133```python134# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",135# on port 123.136transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))137async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:138 ...139```140141See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.142143### ASGI startup and shutdown144145It is not in the scope of HTTPX to trigger ASGI lifespan events of your app.146147However it is suggested to use `LifespanManager` from [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage) in pair with `AsyncClient`.148149## Custom transports150151A transport instance must implement the low-level Transport API, which deals152with sending a single request, and returning a response. You should either
249 unmodified lines
modified:docs/async.md+1 added-51 removed
189 unmodified lines
190```191192## Calling into Python Web Apps193194Just as `httpx.Client` allows you to call directly into WSGI web applications,195the `httpx.AsyncClient` class allows you to call directly into ASGI web applications.196197Let's take this Starlette application as an example:198199```python200from starlette.applications import Starlette201from starlette.responses import HTMLResponse202from starlette.routing import Route203204205async def hello(request):206 return HTMLResponse("Hello World!")207208209app = Starlette(routes=[Route("/", hello)])210```211212We can make requests directly against the application, like so:213214```pycon215>>> import httpx216>>> async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:217... r = await client.get("/")218... assert r.status_code == 200219... assert r.text == "Hello World!"220```221222For some more complex cases you might need to customise the ASGI transport. This allows you to:223224* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.225* Mount the ASGI application at a subpath by setting `root_path`.226* Use a given client address for requests by setting `client`.227228For example:229230```python231# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",232# on port 123.233transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))234async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:235 ...236```237238See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.239240## Startup/shutdown of ASGI apps241242It is not in the scope of HTTPX to trigger lifespan events of your app.243244However it is suggested to use `LifespanManager` from [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage) in pair with `AsyncClient`.194For details on calling directly into ASGI applications, see [the `ASGITransport` docs](../advanced/transports#asgitransport).
modified:httpx/_client.py+15 added-1 removed
670 unmodified lines
671 warnings.warn(message, DeprecationWarning)672 if proxy:673 raise RuntimeError("Use either `proxy` or 'proxies', not both.")674675 if app:676 message = (677 "The 'app' shortcut is now deprecated."678 " Use the explicit style 'transport=WSGITransport(app=...)' instead."679 )680 warnings.warn(message, DeprecationWarning)681682 allow_env_proxies = trust_env and app is None and transport is None683 proxy_map = self._get_proxy_map(proxies or proxy, allow_env_proxies)684685 self._transport = self._init_transport(
731 unmodified lines
1417 warnings.warn(message, DeprecationWarning)1418 if proxy:1419 raise RuntimeError("Use either `proxy` or 'proxies', not both.")14201421 if app:1422 message = (1423 "The 'app' shortcut is now deprecated."1424 " Use the explicit style 'transport=ASGITransport(app=...)' instead."1425 )1426 warnings.warn(message, DeprecationWarning)14271414 allow_env_proxies = trust_env and app is None and transport is None1428 allow_env_proxies = trust_env and transport is None1429 proxy_map = self._get_proxy_map(proxies or proxy, allow_env_proxies)14301431 self._transport = self._init_transport(1432 verify=verify,
620 unmodified lines
modified:tests/test_asgi.py+28 added-9 removed
90 unmodified lines
919293@pytest.mark.anyio94async def test_asgi():95 transport = httpx.ASGITransport(app=hello_world)95 async with httpx.AsyncClient(app=hello_world) as client:96 async with httpx.AsyncClient(transport=transport) as client:97 response = await client.get("http://www.example.org/")9899 assert response.status_code == 200100 assert response.text == "Hello, World!"101102103@pytest.mark.anyio104async def test_asgi_urlencoded_path():105 transport = httpx.ASGITransport(app=echo_path)104 async with httpx.AsyncClient(app=echo_path) as client:106 async with httpx.AsyncClient(transport=transport) as client:107 url = httpx.URL("http://www.example.org/").copy_with(path="/user@example.org")108 response = await client.get(url)109110 assert response.status_code == 200
1 unmodified line
112113114@pytest.mark.anyio115async def test_asgi_raw_path():116 transport = httpx.ASGITransport(app=echo_raw_path)114 async with httpx.AsyncClient(app=echo_raw_path) as client:117 async with httpx.AsyncClient(transport=transport) as client:118 url = httpx.URL("http://www.example.org/").copy_with(path="/user@example.org")119 response = await client.get(url)120121 assert response.status_code == 200
4 unmodified lines
126async def test_asgi_raw_path_should_not_include_querystring_portion():127 """128 See https://github.com/encode/httpx/issues/2810129 """130 transport = httpx.ASGITransport(app=echo_raw_path)127 async with httpx.AsyncClient(app=echo_raw_path) as client:131 async with httpx.AsyncClient(transport=transport) as client:132 url = httpx.URL("http://www.example.org/path?query")133 response = await client.get(url)134135 assert response.status_code == 200
1 unmodified line
137138139@pytest.mark.anyio140async def test_asgi_upload():141 transport = httpx.ASGITransport(app=echo_body)137 async with httpx.AsyncClient(app=echo_body) as client:142 async with httpx.AsyncClient(transport=transport) as client:143 response = await client.post("http://www.example.org/", content=b"example")144145 assert response.status_code == 200146 assert response.text == "example"147148149@pytest.mark.anyio150async def test_asgi_headers():151 transport = httpx.ASGITransport(app=echo_headers)146 async with httpx.AsyncClient(app=echo_headers) as client:152 async with httpx.AsyncClient(transport=transport) as client:153 response = await client.get("http://www.example.org/")154155 assert response.status_code == 200156 assert response.json() == {
8 unmodified lines
165166167@pytest.mark.anyio168async def test_asgi_exc():169 transport = httpx.ASGITransport(app=raise_exc)163 async with httpx.AsyncClient(app=raise_exc) as client:170 async with httpx.AsyncClient(transport=transport) as client:171 with pytest.raises(RuntimeError):172 await client.get("http://www.example.org/")173174175@pytest.mark.anyio176async def test_asgi_exc_after_response():177 transport = httpx.ASGITransport(app=raise_exc_after_response)170 async with httpx.AsyncClient(app=raise_exc_after_response) as client:178 async with httpx.AsyncClient(transport=transport) as client:179 with pytest.raises(RuntimeError):180 await client.get("http://www.example.org/")181182
23 unmodified lines
206 # So if receive() is called again, the disconnect message should be received207 message = await receive()208 disconnect = message.get("type") == "http.disconnect"209210 transport = httpx.ASGITransport(app=read_body)202 async with httpx.AsyncClient(app=read_body) as client:211 async with httpx.AsyncClient(transport=transport) as client:212 response = await client.post("http://www.example.org/", content=b"example")213214 assert response.status_code == 200215 assert disconnect
5 unmodified lines
221 async with httpx.AsyncClient(transport=transport) as client:222 response = await client.get("http://www.example.org/")223224 assert response.status_code == 500225226227@pytest.mark.anyio228async def test_deprecated_shortcut():229 """230 The `app=...` shortcut is now deprecated.231 Use the explicit transport style instead.232 """233 with pytest.warns(DeprecationWarning):234 httpx.AsyncClient(app=hello_world)
modified:tests/test_wsgi.py+27 added-9 removed
90 unmodified lines
91 return echo_body(environ, start_response)929394def test_wsgi():95 client = httpx.Client(app=application_factory([b"Hello, World!"]))95 transport = httpx.WSGITransport(app=application_factory([b"Hello, World!"]))96 client = httpx.Client(transport=transport)97 response = client.get("http://www.example.org/")98 assert response.status_code == 20099 assert response.text == "Hello, World!"100101102def test_wsgi_upload():102 client = httpx.Client(app=echo_body)103 transport = httpx.WSGITransport(app=echo_body)104 client = httpx.Client(transport=transport)105 response = client.post("http://www.example.org/", content=b"example")106 assert response.status_code == 200107 assert response.text == "example"108109110def test_wsgi_upload_with_response_stream():109 client = httpx.Client(app=echo_body_with_response_stream)111 transport = httpx.WSGITransport(app=echo_body_with_response_stream)112 client = httpx.Client(transport=transport)113 response = client.post("http://www.example.org/", content=b"example")114 assert response.status_code == 200115 assert response.text == "example"116117118def test_wsgi_exc():116 client = httpx.Client(app=raise_exc)119 transport = httpx.WSGITransport(app=raise_exc)120 client = httpx.Client(transport=transport)121 with pytest.raises(ValueError):122 client.get("http://www.example.org/")123124125def test_wsgi_http_error():122 client = httpx.Client(app=partial(raise_exc, exc=RuntimeError))126 transport = httpx.WSGITransport(app=partial(raise_exc, exc=RuntimeError))127 client = httpx.Client(transport=transport)128 with pytest.raises(RuntimeError):129 client.get("http://www.example.org/")130131132def test_wsgi_generator():133 output = [b"", b"", b"Some content", b" and more content"]129 client = httpx.Client(app=application_factory(output))134 transport = httpx.WSGITransport(app=application_factory(output))135 client = httpx.Client(transport=transport)136 response = client.get("http://www.example.org/")137 assert response.status_code == 200138 assert response.text == "Some content and more content"139140141def test_wsgi_generator_empty():142 output = [b"", b"", b"", b""]137 client = httpx.Client(app=application_factory(output))143 transport = httpx.WSGITransport(app=application_factory(output))144 client = httpx.Client(transport=transport)145 response = client.get("http://www.example.org/")146 assert response.status_code == 200147 assert response.text == ""148
27 unmodified lines
176 nonlocal server_port177 server_port = environ["SERVER_PORT"]178 return hello_world_app(environ, start_response)179173 client = httpx.Client(app=app)180 transport = httpx.WSGITransport(app=app)181 client = httpx.Client(transport=transport)182 response = client.get(url)183 assert response.status_code == 200184 assert response.text == "Hello, World!"185 assert server_port == expected_server_port
7 unmodified lines
193 server_protocol = environ["SERVER_PROTOCOL"]194 start_response("200 OK", [("Content-Type", "text/plain")])195 return [b"success"]196197 transport = httpx.WSGITransport(app=app)189 with httpx.Client(app=app, base_url="http://testserver") as client:198 with httpx.Client(transport=transport, base_url="http://testserver") as client:199 response = client.get("/")200201 assert response.status_code == 200202 assert response.text == "success"203 assert server_protocol == "HTTP/1.1"204205206def test_deprecated_shortcut():207 """208 The `app=...` shortcut is now deprecated.209 Use the explicit transport style instead.210 """211 with pytest.warns(DeprecationWarning):212 httpx.Client(app=application_factory([b"Hello, World!"]))
modified:CHANGELOG.md+4 added
4 unmodified lines
5The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).67## Unreleased89### Deprecated1011* The `app=...` shortcut has been deprecated. Use the explicit style of `transport=httpx.WSGITransport()` or `transport=httpx.ASGITransport()` instead.1213### Fixed1415* Respect the `http1` argument while configuring proxy transports. (#3023)16* Fix RFC 2069 mode digest authentication. (#3045)
1067 unmodified lines