async.md
This file
Path
docs/async.md
241 lines · 7.6 KiB · Markdown
Last changed by
Removed curio from async.md (#2240)Kieran Klukasbefore adoption940d61b
History of this fileTake it
The walk stopped after 200 commits: lines older than 885314a point at it.
Bump wheel from 0.36.2 to 0.37.0 (#1878)dependabot[bot]before adoption885314a
lines 1–111why, 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`.1617```pycon18>>> async with httpx.AsyncClient() as client:19... r = await client.get('https://www.example.com/')20...21>>> 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.6768```pycon69>>> client = httpx.AsyncClient()70>>> async with client.stream('GET', 'https://www.example.com/') as response:71... async for chunk in response.aiter_bytes():72... ...73```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.82* `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.103104### 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 content111Do not recommend the deprecated `data=` kwarg for passing bytes. (#2044)Vytautas Liuoliabefore adoptiond299e6f
line 112why, one step back112await client.post(url, content=upload_bytes())Bump wheel from 0.36.2 to 0.37.0 (#1878)dependabot[bot]before adoption885314a
lines 113–241why, one step back113```114115### Explicit transport instances116117When instantiating a transport instance directly, you need to use `httpx.AsyncHTTPTransport`.118119For instance:120121```pycon122>>> import httpx123>>> transport = httpx.AsyncHTTPTransport(retries=1)124>>> async with httpx.AsyncClient(transport=transport) as client:125>>> ...126```127128## Supported async environments129130HTTPX supports either `asyncio` or `trio` as an async environment.131132It will auto-detect which of those two to use as the backend133for socket operations and concurrency primitives.134135### [AsyncIO](https://docs.python.org/3/library/asyncio.html)136137AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)138for writing concurrent code with the async/await syntax.139140```python141import asyncio142import httpx143144async def main():145 async with httpx.AsyncClient() as client:146 response = await client.get('https://www.example.com/')147 print(response)148149asyncio.run(main())150```151152### [Trio](https://github.com/python-trio/trio)153154Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),155designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).156157```python158import httpx159import trio160161async def main():162 async with httpx.AsyncClient() as client:163 response = await client.get('https://www.example.com/')164 print(response)165166trio.run(main)167```168169!!! important170 The `trio` package must be installed to use the Trio backend.171172173### [AnyIO](https://github.com/agronholm/anyio)174175AnyIO is an [asynchronous networking and concurrency library](https://anyio.readthedocs.io/) that works on top of either `asyncio` or `trio`. It blends in with native libraries of your chosen backend (defaults to `asyncio`).176177```python178import httpx179import anyio180181async def main():182 async with httpx.AsyncClient() as client:183 response = await client.get('https://www.example.com/')184 print(response)185186anyio.run(main, backend='trio')187```188189## Calling into Python Web Apps190191Just as `httpx.Client` allows you to call directly into WSGI web applications,192the `httpx.AsyncClient` class allows you to call directly into ASGI web applications.193194Let's take this Starlette application as an example:195196```python197from starlette.applications import Starlette198from starlette.responses import HTMLResponse199from starlette.routing import Route200201202async def hello(request):203 return HTMLResponse("Hello World!")204205206app = Starlette(routes=[Route("/", hello)])207```208209We can make requests directly against the application, like so:210211```pycon212>>> import httpx213>>> async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:214... r = await client.get("/")215... assert r.status_code == 200216... assert r.text == "Hello World!"217```218219For some more complex cases you might need to customise the ASGI transport. This allows you to:220221* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.222* Mount the ASGI application at a subpath by setting `root_path`.223* Use a given client address for requests by setting `client`.224225For example:226227```python228# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",229# on port 123.230transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))231async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:232 ...233```234235See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.236237## Startup/shutdown of ASGI apps238239It is not in the scope of HTTPX to trigger lifespan events of your app.240241However it is suggested to use `LifespanManager` from [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage) in pair with `AsyncClient`.