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
Provenance
- Commit
cabd1c0- Tree
889bbd1- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
6f46152
6 files changed+145 added−72 removed
modified:docs/advanced/transports.md+70 added-2 removed
40 unmodified lines41 42 This is particularly useful for two main use-cases:43 44 * 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.46 47+### Example48+49 Here's an example of integrating against a Flask application:50 51 ```python52 from flask import Flask5 unmodified lines58 @app.route("/")59 def hello():60 return "Hello World!"61 62+transport = httpx.WSGITransport(app=app)60-with httpx.Client(app=app, base_url="http://testserver") as client:63+with 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 ```68 69+### Configuration70+71 For some more complex cases you might need to customize the WSGI transport. This allows you to:72 73 * 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 lines82 with httpx.Client(transport=transport, base_url="http://testserver") as client:83 ...84 ```85 86+## ASGITransport87+88+You can configure an `httpx` client to call directly into an async Python web application using the ASGI protocol.89+90+This is particularly useful for two main use-cases:91+92+* Using `httpx` as a client inside test cases.93+* Mocking out external services during tests or in dev or staging environments.94+95+### Example96+97+Let's take this Starlette application as an example:98+99+```python100+from starlette.applications import Starlette101+from starlette.responses import HTMLResponse102+from starlette.routing import Route103+104+105+async def hello(request):106+ return HTMLResponse("Hello World!")107+108+109+app = Starlette(routes=[Route("/", hello)])110+```111+112+We can make requests directly against the application, like so:113+114+```python115+transport = httpx.ASGITransport(app=app)116+117+async 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+```122+123+### Configuration124+125+For some more complex cases you might need to customise the ASGI transport. This allows you to:126+127+* 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`.130+131+For example:132+133+```python134+# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",135+# on port 123.136+transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))137+async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:138+ ...139+```140+141+See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.142+143+### ASGI startup and shutdown144+145+It is not in the scope of HTTPX to trigger ASGI lifespan events of your app.146+147+However it is suggested to use `LifespanManager` from [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage) in pair with `AsyncClient`.148+149 ## Custom transports150 151 A transport instance must implement the low-level Transport API, which deals152 with sending a single request, and returning a response. You should either249 unmodified linesmodified:docs/async.md+1 added-51 removed
189 unmodified lines190 ```191 192 ## Calling into Python Web Apps193 194-Just as `httpx.Client` allows you to call directly into WSGI web applications,195-the `httpx.AsyncClient` class allows you to call directly into ASGI web applications.196-197-Let's take this Starlette application as an example:198-199-```python200-from starlette.applications import Starlette201-from starlette.responses import HTMLResponse202-from starlette.routing import Route203-204-205-async def hello(request):206- return HTMLResponse("Hello World!")207-208-209-app = Starlette(routes=[Route("/", hello)])210-```211-212-We can make requests directly against the application, like so:213-214-```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-```221-222-For some more complex cases you might need to customise the ASGI transport. This allows you to:223-224-* 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`.227-228-For example:229-230-```python231-# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",232-# on port 123.233-transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))234-async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:235- ...236-```237-238-See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.239-240-## Startup/shutdown of ASGI apps241-242-It is not in the scope of HTTPX to trigger lifespan events of your app.243-244-However it is suggested to use `LifespanManager` from [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage) in pair with `AsyncClient`.194+For details on calling directly into ASGI applications, see [the `ASGITransport` docs](../advanced/transports#asgitransport).modified:httpx/_client.py+15 added-1 removed
670 unmodified lines671 warnings.warn(message, DeprecationWarning)672 if proxy:673 raise RuntimeError("Use either `proxy` or 'proxies', not both.")674 675+ 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)681+682 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)684 685 self._transport = self._init_transport(731 unmodified lines1417 warnings.warn(message, DeprecationWarning)1418 if proxy:1419 raise RuntimeError("Use either `proxy` or 'proxies', not both.")1420 1421+ 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)1427+1414- 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)1430 1431 self._transport = self._init_transport(1432 verify=verify,620 unmodified linesmodified:tests/test_asgi.py+28 added-9 removed
90 unmodified lines91 92 93 @pytest.mark.anyio94 async 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/")98 99 assert response.status_code == 200100 assert response.text == "Hello, World!"101 102 103 @pytest.mark.anyio104 async 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)109 110 assert response.status_code == 2001 unmodified line112 113 114 @pytest.mark.anyio115 async 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)120 121 assert response.status_code == 2004 unmodified lines126 async 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)134 135 assert response.status_code == 2001 unmodified line137 138 139 @pytest.mark.anyio140 async 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")144 145 assert response.status_code == 200146 assert response.text == "example"147 148 149 @pytest.mark.anyio150 async 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/")154 155 assert response.status_code == 200156 assert response.json() == {8 unmodified lines165 166 167 @pytest.mark.anyio168 async 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/")173 174 175 @pytest.mark.anyio176 async 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/")181 182 23 unmodified lines206 # So if receive() is called again, the disconnect message should be received207 message = await receive()208 disconnect = message.get("type") == "http.disconnect"209 210+ 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")213 214 assert response.status_code == 200215 assert disconnect5 unmodified lines221 async with httpx.AsyncClient(transport=transport) as client:222 response = await client.get("http://www.example.org/")223 224 assert response.status_code == 500225+226+227+@pytest.mark.anyio228+async 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 lines91 return echo_body(environ, start_response)92 93 94 def 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!"100 101 102 def 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"108 109 110 def 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"116 117 118 def 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/")123 124 125 def 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/")130 131 132 def 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"139 140 141 def 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 lines176 nonlocal server_port177 server_port = environ["SERVER_PORT"]178 return hello_world_app(environ, start_response)179 173- 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_port7 unmodified lines193 server_protocol = environ["SERVER_PROTOCOL"]194 start_response("200 OK", [("Content-Type", "text/plain")])195 return [b"success"]196 197+ 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("/")200 201 assert response.status_code == 200202 assert response.text == "success"203 assert server_protocol == "HTTP/1.1"204+205+206+def 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 lines5 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).6 7 ## Unreleased8 9+### Deprecated10+11+* The `app=...` shortcut has been deprecated. Use the explicit style of `transport=httpx.WSGITransport()` or `transport=httpx.ASGITransport()` instead.12+13 ### Fixed14 15 * Respect the `http1` argument while configuring proxy transports. (#3023)16 * Fix RFC 2069 mode digest authentication. (#3045)1067 unmodified lines