Skip to content
Myr

async.md

This file

Path

docs/async.md

244 lines · 7.9 KiB · Markdown

Last changed by

async recommendations (#2727)Trond Hindenesbefore adoption6d183a8

History of this file

Take it

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

Drop multipart requirement from tests (#2456)Tom Christiebefore adoption883cf8c

lines 1–55why, 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!!! 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```55

async recommendations (#2727)Trond Hindenesbefore adoption6d183a8

lines 56–58why, one step back
56!!! warning
57In 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.58

Drop multipart requirement from tests (#2456)Tom Christiebefore adoption883cf8c

lines 59–244why, one step back
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.8687For 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)`.8889Example 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 Apps193194Just as `httpx.Client` allows you to call directly into WSGI web applications,195the `httpx.AsyncClient` class allows you to call directly into ASGI web applications.196197Let's take this Starlette application as an example:198199```python200from starlette.applications import Starlette201from starlette.responses import HTMLResponse202from starlette.routing import Route203204205async def hello(request):206 return HTMLResponse("Hello World!")207208209app = Starlette(routes=[Route("/", hello)])210```211212We can make requests directly against the application, like so:213214```pycon215>>> import httpx216>>> async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:217... r = await client.get("/")218... assert r.status_code == 200219... assert r.text == "Hello World!"220```221222For some more complex cases you might need to customise the ASGI transport. This allows you to:223224* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.225* Mount the ASGI application at a subpath by setting `root_path`.226* Use a given client address for requests by setting `client`.227228For example:229230```python231# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",232# on port 123.233transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))234async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:235 ...236```237238See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.239240## Startup/shutdown of ASGI apps241242It is not in the scope of HTTPX to trigger lifespan events of your app.243244However it is suggested to use `LifespanManager` from [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage) in pair with `AsyncClient`.