Skip to content
Myr

async.md

This file

Path

docs/async.md

194 lines · 6.3 KiB · Markdown

Last changed by

Drop Python 3.8 support (#3592)Alex Grönholmbefore adoption4fb9528

History of this file

Take it

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

Bump ruff from 0.0.260 to 0.0.275 (#2753)dependabot[bot]before adoption9d022c0

lines 1–25why, one step back
1# Async Support
23HTTPX 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!!! tip

Drop Python 3.8 support (#3592)Alex Grönholmbefore adoption4fb9528

line 26why, one step back
26 Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.9+ with `python -m asyncio` to try this code interactively, as they support executing `async`/`await` expressions in the console.

Bump ruff from 0.0.260 to 0.0.275 (#2753)dependabot[bot]before adoption9d022c0

lines 27–56why, one step back
27
28## 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```5556!!! warning

Adding an indent to fix wrong rendering in warning block (#3056)Nyakku Shigurebefore adoptiond76607b

line 57why, one step back
57 In order to get the most benefit from connection pooling, make sure you're not instantiating multiple client instances - for example by using `async with` inside a "hot loop". This can be achieved either by having a single scoped client that's passed throughout wherever it's needed, or by having a single global client instance.

Bump ruff from 0.0.260 to 0.0.275 (#2753)dependabot[bot]before adoption9d022c0

lines 58–86why, one step back
58
59Alternatively, use `await client.aclose()` if you want to close a client explicitly:6061```python62client = httpx.AsyncClient()63...64await client.aclose()65```6667### Streaming responses6869The `AsyncClient.stream(method, url, ...)` method is an async context block.7071```pycon72>>> client = httpx.AsyncClient()73>>> async with client.stream('GET', 'https://www.example.com/') as response:74... async for chunk in response.aiter_bytes():75... ...76```7778The async response streaming methods are:7980* `Response.aread()` - For conditionally reading a response inside a stream block.81* `Response.aiter_bytes()` - For streaming the response content as bytes.82* `Response.aiter_text()` - For streaming the response content as text.83* `Response.aiter_lines()` - For streaming the response content as lines of text.84* `Response.aiter_raw()` - For streaming the raw response bytes, without applying content decoding.85* `Response.aclose()` - For closing the response. You don't usually need this, since `.stream` block closes the response automatically on exit.86

Fix sections references (#3058)Kar Petrosyanbefore adoption73e6888

line 87why, one step back
87For situations when context block usage is not practical, it is possible to enter "manual mode" by sending a [`Request` instance](advanced/clients.md#request-instances) using `client.send(..., stream=True)`.

Bump ruff from 0.0.260 to 0.0.275 (#2753)dependabot[bot]before adoption9d022c0

lines 88–193why, one step back
88
89Example in the context of forwarding the response to a streaming web endpoint with [Starlette](https://www.starlette.io):9091```python92import httpx93from starlette.background import BackgroundTask94from starlette.responses import StreamingResponse9596client = httpx.AsyncClient()9798async def home(request):99 req = client.build_request("GET", "https://www.example.com/")100 r = await client.send(req, stream=True)101 return StreamingResponse(r.aiter_text(), background=BackgroundTask(r.aclose))102```103104!!! warning105 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.106107### Streaming requests108109When sending a streaming request body with an `AsyncClient` instance, you should use an async bytes generator instead of a bytes generator:110111```python112async def upload_bytes():113 ... # yield byte content114115await client.post(url, content=upload_bytes())116```117118### Explicit transport instances119120When instantiating a transport instance directly, you need to use `httpx.AsyncHTTPTransport`.121122For instance:123124```pycon125>>> import httpx126>>> transport = httpx.AsyncHTTPTransport(retries=1)127>>> async with httpx.AsyncClient(transport=transport) as client:128>>> ...129```130131## Supported async environments132133HTTPX supports either `asyncio` or `trio` as an async environment.134135It will auto-detect which of those two to use as the backend136for socket operations and concurrency primitives.137138### [AsyncIO](https://docs.python.org/3/library/asyncio.html)139140AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)141for writing concurrent code with the async/await syntax.142143```python144import asyncio145import httpx146147async def main():148 async with httpx.AsyncClient() as client:149 response = await client.get('https://www.example.com/')150 print(response)151152asyncio.run(main())153```154155### [Trio](https://github.com/python-trio/trio)156157Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),158designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).159160```python161import httpx162import trio163164async def main():165 async with httpx.AsyncClient() as client:166 response = await client.get('https://www.example.com/')167 print(response)168169trio.run(main)170```171172!!! important173 The `trio` package must be installed to use the Trio backend.174175176### [AnyIO](https://github.com/agronholm/anyio)177178AnyIO 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`).179180```python181import httpx182import anyio183184async def main():185 async with httpx.AsyncClient() as client:186 response = await client.get('https://www.example.com/')187 print(response)188189anyio.run(main, backend='trio')190```191192## Calling into Python Web Apps193

Deprecate `app=...` in favor of explicit `WSGITransport`/`ASGITransport`. (#3050)Tom Christiebefore adoptioncabd1c0

line 194why, one step back
194For details on calling directly into ASGI applications, see [the `ASGITransport` docs](../advanced/transports#asgitransport).