Skip to content
Myr

async.md

This file

Path

docs/async.md

142 lines · 4.2 KiB · Markdown

Last changed by

Document when to use AsyncClient (#534)Florimond Mancabefore adoption926d6cd

History of this file

Take it

The walk stopped after 200 commits: lines older than f9e3ad4 point at it.

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 1–2why, one step back
1# Async Client
2

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 3why, one step back
3HTTPX offers a standard synchronous API by default, but also gives you

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 4–17why, one step back
4the 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```python

Document + recommend async with syntax for AsyncClient (#344)Florimond Mancabefore adoption4616031

lines 18–21why, one step back
18>>> async with httpx.AsyncClient() as client:
19>>> r = await client.get('https://www.example.com/')20>>> r21<Response [200 OK]>

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 22–23why, one step back
22```
23

Document + recommend async with syntax for AsyncClient (#344)Florimond Mancabefore adoption4616031

lines 24–31why, one step back
24!!! tip
25 Use [IPython](https://ipython.readthedocs.io/en/stable/) to try this code interactively, as it supports executing `async`/`await` expressions in the console.2627!!! note28 The `async with` syntax ensures that all active connections are closed on exit.2930 It is safe to access response content (e.g. `r.text`) both inside and outside the `async with` block, unless you are using response streaming. In that case, you should `.read()`, `.stream()`, or `.close()` the response *inside* the `async with` block.31

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 32–37why, one step back
32## API Differences
3334If you're using streaming responses then there are a few bits of API that35use async methods:3637```python

Document + recommend async with syntax for AsyncClient (#344)Florimond Mancabefore adoption4616031

lines 38–39why, one step back
38>>> async with httpx.AsyncClient() as client:
39>>> r = await client.get('https://www.example.com/', stream=True)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 40–50why, one step back
40>>> async for chunk in r.stream():
41>>> ...42```4344The async response methods are:4546* `.read()`47* `.stream()`48* `.raw()`49* `.close()`50

Fix link to parallel page from async page (#440)nwalsh1995before adoptionf504399

line 51why, one step back
51If you're making [parallel requests](parallel.md), then you'll also need to use an async API:

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 52–53why, one step back
52
53```python

Document + recommend async with syntax for AsyncClient (#344)Florimond Mancabefore adoption4616031

lines 54–59why, one step back
54>>> async with httpx.AsyncClient() as client:
55>>> async with client.parallel() as parallel:56>>> pending_one = parallel.get('https://example.com/1')57>>> pending_two = parallel.get('https://example.com/2')58>>> response_one = await pending_one.get_response()59>>> response_two = await pending_two.get_response()

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 60–66why, one step back
60```
6162The async parallel methods are:6364* `.parallel()` *Used as an "async with" context manager.*65* `.get_response()`66* `.next_response()`

Document supported async libraries (#387)Florimond Mancabefore adoption3496525

lines 67–107why, one step back
67
68## Supported async libraries6970You can use `AsyncClient` with any of the following async libraries.7172!!! tip73 You will typically be using `AsyncClient` in async programs that run on `asyncio`. If that's the case, or if you're not sure what this is all about, you can safely ignore this section.7475### [asyncio](https://docs.python.org/3/library/asyncio.html) (Default)7677By default, `AsyncClient` uses `asyncio` to perform asynchronous operations and I/O calls.7879```python80import asyncio81import httpx8283async def main():84 async with httpx.AsyncClient() as client:85 ...8687asyncio.run(main())88```8990### [trio](https://github.com/python-trio/trio)9192To make asynchronous requests in `trio` programs, pass a `TrioBackend` to the `AsyncClient`:9394```python95import trio96import httpx97from httpx.concurrency.trio import TrioBackend9899async def main():100 async with httpx.AsyncClient(backend=TrioBackend()) as client:101 ...102103trio.run(main)104```105106!!! important107 `trio` must be installed to import and use the `TrioBackend`.

Document when to use AsyncClient (#534)Florimond Mancabefore adoption926d6cd

lines 108–142why, one step back
108
109## FAQ110111### When should I use an `AsyncClient`?112113You should use an `AsyncClient` whenever you are inside an *async environment*.114115In particular, using `httpx.get()` or `httpx.Client()` in an async environment is **not** supported. There are several technical reasons to this, but the rationale is that you shouldn't be doing blocking-style network calls in the context of an event loop (for more discussion, see [#179](https://github.com/encode/httpx/issues/179)).116117For example, this won't work:118119```python120import asyncio121import httpx122123async def main():124 r = httpx.get("https://example.org")125126asyncio.run(main())127```128129Instead, you should use an `AsyncClient`:130131```python132import asyncio133import httpx134135async def main():136 async with httpx.AsyncClient() as client:137 r = await client.get("https://example.org")138139asyncio.run(main())140```141142If you *need* to make synchronous requests, or otherwise run into issues related to sync usage, you should probably consider using a regular threaded client such as [Requests](https://github.com/psf/requests) instead.