Skip to content
Myr

async.md

This file

Path

docs/async.md

201 lines · 6.1 KiB · Markdown

Last changed by

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

History of this file

Take it

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 1–69why, 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```python18>>> async with httpx.AsyncClient() as client:19>>> r = await client.get('https://www.example.com/')20>>> r21<Response [200 OK]>22```2324!!! tip25 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.2627## API Differences2829If you're using an async client then there are a few bits of API that30use async methods.3132### Making requests3334The request methods are all async, so you should use `response = await client.get(...)` style for all of the following:3536* `AsyncClient.get(url, ...)`37* `AsyncClient.options(url, ...)`38* `AsyncClient.head(url, ...)`39* `AsyncClient.post(url, ...)`40* `AsyncClient.put(url, ...)`41* `AsyncClient.patch(url, ...)`42* `AsyncClient.delete(url, ...)`43* `AsyncClient.request(method, url, ...)`44* `AsyncClient.send(request, ...)`4546### Opening and closing clients4748Use `async with httpx.AsyncClient()` if you want a context-managed client...4950```python51async with httpx.AsyncClient() as client:52 ...53```5455Alternatively, use `await client.aclose()` if you want to close a client explicitly:5657```python58client = httpx.AsyncClient()59...60await client.aclose()61```6263### Streaming responses6465The `AsyncClient.stream(method, url, ...)` method is an async context block.6667```python68>>> client = httpx.AsyncClient()69>>> async with client.stream('GET', 'https://www.example.com/') as response:

Fix typo in 'Streaming responses' docs (#744)Luís Gustavobefore adoptionc225e95

line 70why, one step back
70>>> async for chunk in response.aiter_bytes():

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 71–76why, one step back
71>>> ...
72```7374The async response streaming methods are:7576* `Response.aread()` - For conditionally reading a response inside a stream block.

Fix typo in 'Streaming responses' docs (#744)Luís Gustavobefore adoptionc225e95

line 77why, one step back
77* `Response.aiter_bytes()` - For streaming the response content as bytes.

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 78–84why, one step back
78* `Response.aiter_text()` - For streaming the response content as text.
79* `Response.aiter_lines()` - For streaming the response content as lines of text.80* `Response.aiter_raw()` - For streaming the raw response bytes, without applying content decoding.81* `Response.aclose()` - For closing the response. You don't usually need this, since `.stream` block close the response automatically on exit.8283### Streaming requests84

Fix typo in async.md (#747)Mason Hallbefore adoptionb112b23

line 85why, one step back
85When sending a streaming request body with an `AsyncClient` instance, you should use an async bytes generator instead of a bytes generator:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 86–97why, one step back
86
87```python88async def upload_bytes():89 ... # yield byte content9091await client.post(url, data=upload_bytes())92```9394## Supported async environments9596HTTPX supports either `asyncio` or `trio` as an async environment.97

Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417

line 98why, one step back
98It will auto-detect which of those two to use as the backend

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 99–161why, one step back
99for socket operations and concurrency primitives.
100101### [AsyncIO](https://docs.python.org/3/library/asyncio.html)102103AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)104for writing concurrent code with the async/await syntax.105106```python107import asyncio108import httpx109110async def main():111 async with httpx.AsyncClient() as client:112 response = await client.get('https://www.example.com/')113 print(response)114115asyncio.run(main())116```117118### [Trio](https://github.com/python-trio/trio)119120Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),121designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).122123```python124import httpx125import trio126127async def main():128 async with httpx.AsyncClient() as client:129 response = await client.get('https://www.example.com/')130 print(response)131132trio.run(main)133```134135!!! important136 The `trio` package must be installed to use the Trio backend.137138## Calling into Python Web Apps139140Just as `httpx.Client` allows you to call directly into WSGI web applications,141the `httpx.AsyncClient` class allows you to call directly into ASGI web applications.142143Let's take this Starlette application as an example:144145```python146from starlette.applications import Starlette147from starlette.responses import HTMLResponse148from starlette.routing import Route149150151async def hello():152 return HTMLResponse("Hello World!")153154155app = Starlette(routes=[Route("/", hello)])156```157158We can make requests directly against the application, like so:159160```python161>>> import httpx

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 162–163why, one step back
162>>> async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:
163... r = await client.get("/")

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 164–167why, one step back
164... assert r.status_code == 200
165... assert r.text == "Hello World!"166```167

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

line 168why, one step back
168For some more complex cases you might need to customise the ASGI transport. This allows you to:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 169–178why, one step back
169
170* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.171* Mount the ASGI application at a subpath by setting `root_path`.172* Use a given client address for requests by setting `client`.173174For example:175176```python177# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",178# on port 123.

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

lines 179–180why, one step back
179transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))
180async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 181–201why, one step back
181 ...
182```183184See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.185186## Unix Domain Sockets187188The async client provides support for connecting through a unix domain socket via the `uds` parameter. This is useful when making requests to a server that is bound to a socket file rather than an IP address.189190Here's an example requesting the Docker Engine API:191192```python193import httpx194195196async with httpx.AsyncClient(uds="/var/run/docker.sock") as client:197 # This request will connect through the socket file.198 resp = await client.get("http://localhost/version")199```200201This functionality is not currently available in the synchronous client.