From: Florimond Manca Date: Fri, 22 Nov 2019 08:19:39 +0000 (+0100) Subject: Document when to use AsyncClient (#534) X-Git-Tag: 0.8.0~6 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=926d6cd6e490bb20558b11b4d640c58ef19c0f72;p=thirdparty%2Fhttpx.git Document when to use AsyncClient (#534) * Document when to use AsyncClient * Strip advice on reverting to Requests --- diff --git a/docs/async.md b/docs/async.md index 45620bf8..c631d545 100644 --- a/docs/async.md +++ b/docs/async.md @@ -105,3 +105,38 @@ trio.run(main) !!! important `trio` must be installed to import and use the `TrioBackend`. + +## FAQ + +### When should I use an `AsyncClient`? + +You should use an `AsyncClient` whenever you are inside an *async environment*. + +In 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)). + +For example, this won't work: + +```python +import asyncio +import httpx + +async def main(): + r = httpx.get("https://example.org") + +asyncio.run(main()) +``` + +Instead, you should use an `AsyncClient`: + +```python +import asyncio +import httpx + +async def main(): + async with httpx.AsyncClient() as client: + r = await client.get("https://example.org") + +asyncio.run(main()) +``` + +If 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.