Skip to content
Myr

async.md

This file

Path

docs/async.md

245 lines · 7.5 KiB · Markdown

Last changed by

added docs for startup/shutdown of ASGI apps (#1554)Jaakko Lappalainenbefore adoptionc1ccdbc

History of this file

Take it

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

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

lines 1–16why, 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`.16

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 17why, one step back
17```pycon

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

line 18why, one step back
18>>> async with httpx.AsyncClient() as client:

Fix typo (#1386)Kyungmin Leebefore adoption84dca25

lines 19–20why, one step back
19... r = await client.get('https://www.example.com/')
20...

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

lines 21–67why, one step back
21>>> r
22<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.67

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 68why, one step back
68```pycon

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

lines 69–70why, one step back
69>>> client = httpx.AsyncClient()
70>>> async with client.stream('GET', 'https://www.example.com/') as response:

Fix typo (#1386)Kyungmin Leebefore adoption84dca25

lines 71–72why, one step back
71... async for chunk in response.aiter_bytes():
72... ...

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

lines 73–114why, one step back
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 content111112await client.post(url, data=upload_bytes())113```114

Add `HTTPTransport` and `AsyncHTTPTransport` (#1399)Tom Christiebefore adoption89fb0cb

lines 115–127why, one step back
115### Explicit transport instances
116117When 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```127

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

lines 128–171why, one step back
128## Supported async environments
129130HTTPX 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.171

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

lines 172–192why, one step back
172
173### [Curio](https://github.com/dabeaz/curio)174175Curio is a [coroutine-based library](https://curio.readthedocs.io/en/latest/tutorial.html)176for concurrent Python systems programming.177178```python179import httpx180import curio181182async def main():183 async with httpx.AsyncClient() as client:184 response = await client.get('https://www.example.com/')185 print(response)186187curio.run(main)188```189190!!! important191 The `curio` package must be installed to use the Curio backend.192

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

lines 193–205why, one step back
193## Calling into Python Web Apps
194195Just as `httpx.Client` allows you to call directly into WSGI web applications,196the `httpx.AsyncClient` class allows you to call directly into ASGI web applications.197198Let's take this Starlette application as an example:199200```python201from starlette.applications import Starlette202from starlette.responses import HTMLResponse203from starlette.routing import Route204205

fix code example, in async.md (#1388)podhmobefore adoptionf8f5430

line 206why, one step back
206async def hello(request):

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

lines 207–214why, one step back
207 return HTMLResponse("Hello World!")
208209210app = Starlette(routes=[Route("/", hello)])211```212213We can make requests directly against the application, like so:214

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 215why, one step back
215```pycon

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

lines 216–239why, one step back
216>>> import httpx
217>>> async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:218... r = await client.get("/")219... assert r.status_code == 200220... assert r.text == "Hello World!"221```222223For some more complex cases you might need to customise the ASGI transport. This allows you to:224225* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.226* Mount the ASGI application at a subpath by setting `root_path`.227* Use a given client address for requests by setting `client`.228229For example:230231```python232# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",233# on port 123.234transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))235async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:236 ...237```238239See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.

added docs for startup/shutdown of ASGI apps (#1554)Jaakko Lappalainenbefore adoptionc1ccdbc

lines 240–245why, one step back
240
241## Startup/shutdown of ASGI apps242243It is not in the scope of HTTPX to trigger lifespan events of your app.244245However it is suggested to use `LifespanManager` from [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage) in pair with `AsyncClient`.