async.md
This file
Path
docs/async.md
226 lines · 7.0 KiB · Markdown
Last changed by
Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9
History of this fileTake it
The walk stopped after 200 commits: lines older than 0296c2b point at it.
Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 1–16why, one step back1# Async Support23HTTPX offers a standard synchronous API by default, but also gives you4the option of an async client if you need it.56Async is a concurrency model that is far more efficient than multi-threading,7and can provide significant performance benefits and enable the use of8long-lived network connections such as WebSockets.910If you're working with an async web framework then you'll also want to use an11async client for sending outgoing HTTP requests.1213## Making Async requests1415To make asynchronous requests, you'll need an `AsyncClient`.16Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 17why, one step back17```pyconType check tests (#1054)Florimond Mancabefore adoption0296c2b
line 18why, one step back18>>> async with httpx.AsyncClient() as client:Fix typo (#1386)Kyungmin Leebefore adoption84dca25
lines 19–20why, one step back19... r = await client.get('https://www.example.com/')20...Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 21–67why, one step back21>>> r22<Response [200 OK]>23```2425!!! tip26 Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.8+ with `python -m asyncio` to try this code interactively, as they support executing `async`/`await` expressions in the console.2728## API Differences2930If you're using an async client then there are a few bits of API that31use async methods.3233### Making requests3435The request methods are all async, so you should use `response = await client.get(...)` style for all of the following:3637* `AsyncClient.get(url, ...)`38* `AsyncClient.options(url, ...)`39* `AsyncClient.head(url, ...)`40* `AsyncClient.post(url, ...)`41* `AsyncClient.put(url, ...)`42* `AsyncClient.patch(url, ...)`43* `AsyncClient.delete(url, ...)`44* `AsyncClient.request(method, url, ...)`45* `AsyncClient.send(request, ...)`4647### Opening and closing clients4849Use `async with httpx.AsyncClient()` if you want a context-managed client...5051```python52async with httpx.AsyncClient() as client:53 ...54```5556Alternatively, use `await client.aclose()` if you want to close a client explicitly:5758```python59client = httpx.AsyncClient()60...61await client.aclose()62```6364### Streaming responses6566The `AsyncClient.stream(method, url, ...)` method is an async context block.67Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 68why, one step back68```pyconType check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 69–70why, one step back69>>> client = httpx.AsyncClient()70>>> async with client.stream('GET', 'https://www.example.com/') as response:Fix typo (#1386)Kyungmin Leebefore adoption84dca25
lines 71–72why, one step back71... async for chunk in response.aiter_bytes():72... ...Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 73–81why, one step back73```7475The async response streaming methods are:7677* `Response.aread()` - For conditionally reading a response inside a stream block.78* `Response.aiter_bytes()` - For streaming the response content as bytes.79* `Response.aiter_text()` - For streaming the response content as text.80* `Response.aiter_lines()` - For streaming the response content as lines of text.81* `Response.aiter_raw()` - For streaming the raw response bytes, without applying content decoding.Add "manual streaming mode" docs (#1046)Florimond Mancabefore adoptiondf24a0f
lines 82–102why, one step back82* `Response.aclose()` - For closing the response. You don't usually need this, since `.stream` block closes the response automatically on exit.8384For situations when context block usage is not practical, it is possible to enter "manual mode" by sending a [`Request` instance](./advanced.md#request-instances) using `client.send(..., stream=True)`.8586Example in the context of forwarding the response to a streaming web endpoint with [Starlette](https://www.starlette.io):8788```python89import httpx90from starlette.background import BackgroundTask91from starlette.responses import StreamingResponse9293client = httpx.AsyncClient()9495async def home(request):96 req = client.build_request("GET", "https://www.example.com/")97 r = await client.send(req, stream=True)98 return StreamingResponse(r.aiter_text(), background=BackgroundTask(r.aclose))99```100101!!! warning102 When using this "manual streaming mode", it is your duty as a developer to make sure that `Response.aclose()` is called eventually. Failing to do so would leave connections open, most likely resulting in resource leaks down the line.Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 103–158why, one step back103104### Streaming requests105106When sending a streaming request body with an `AsyncClient` instance, you should use an async bytes generator instead of a bytes generator:107108```python109async def upload_bytes():110 ... # yield byte content111112await client.post(url, data=upload_bytes())113```114115## Supported async environments116117HTTPX supports either `asyncio` or `trio` as an async environment.118119It will auto-detect which of those two to use as the backend120for socket operations and concurrency primitives.121122### [AsyncIO](https://docs.python.org/3/library/asyncio.html)123124AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)125for writing concurrent code with the async/await syntax.126127```python128import asyncio129import httpx130131async def main():132 async with httpx.AsyncClient() as client:133 response = await client.get('https://www.example.com/')134 print(response)135136asyncio.run(main())137```138139### [Trio](https://github.com/python-trio/trio)140141Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),142designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).143144```python145import httpx146import trio147148async def main():149 async with httpx.AsyncClient() as client:150 response = await client.get('https://www.example.com/')151 print(response)152153trio.run(main)154```155156!!! important157 The `trio` package must be installed to use the Trio backend.158Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9
lines 159–179why, one step back159160### [Curio](https://github.com/dabeaz/curio)161162Curio is a [coroutine-based library](https://curio.readthedocs.io/en/latest/tutorial.html)163for concurrent Python systems programming.164165```python166import httpx167import curio168169async def main():170 async with httpx.AsyncClient() as client:171 response = await client.get('https://www.example.com/')172 print(response)173174curio.run(main)175```176177!!! important178 The `curio` package must be installed to use the Curio backend.179Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 180–192why, one step back180## Calling into Python Web Apps181182Just as `httpx.Client` allows you to call directly into WSGI web applications,183the `httpx.AsyncClient` class allows you to call directly into ASGI web applications.184185Let's take this Starlette application as an example:186187```python188from starlette.applications import Starlette189from starlette.responses import HTMLResponse190from starlette.routing import Route191192fix code example, in async.md (#1388)podhmobefore adoptionf8f5430
line 193why, one step back193async def hello(request):Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 194–201why, one step back194 return HTMLResponse("Hello World!")195196197app = Starlette(routes=[Route("/", hello)])198```199200We can make requests directly against the application, like so:201Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 202why, one step back202```pyconType check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 203–226why, one step back203>>> import httpx204>>> async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:205... r = await client.get("/")206... assert r.status_code == 200207... assert r.text == "Hello World!"208```209210For some more complex cases you might need to customise the ASGI transport. This allows you to:211212* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.213* Mount the ASGI application at a subpath by setting `root_path`.214* Use a given client address for requests by setting `client`.215216For example:217218```python219# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",220# on port 123.221transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))222async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:223 ...224```225226See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.