Skip to content
Myr

async.md

This file

Path

docs/async.md

210 lines · 6.5 KiB · Markdown

Last changed by

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

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–170why, 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.9798By default it will auto-detect which of those two to use as the backend99for socket operations and concurrency primitives.100101You can also explicitly select a backend by instantiating a client with the102`backend` argument...103104```python105client = httpx.AsyncClient(backend='auto') # Autodetection. The default case.106client = httpx.AsyncClient(backend='asyncio') # Use asyncio as the backend.107client = httpx.AsyncClient(backend='trio') # Use trio as the backend.108```109110### [AsyncIO](https://docs.python.org/3/library/asyncio.html)111112AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)113for writing concurrent code with the async/await syntax.114115```python116import asyncio117import httpx118119async def main():120 async with httpx.AsyncClient() as client:121 response = await client.get('https://www.example.com/')122 print(response)123124asyncio.run(main())125```126127### [Trio](https://github.com/python-trio/trio)128129Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),130designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).131132```python133import httpx134import trio135136async def main():137 async with httpx.AsyncClient() as client:138 response = await client.get('https://www.example.com/')139 print(response)140141trio.run(main)142```143144!!! important145 The `trio` package must be installed to use the Trio backend.146147## Calling into Python Web Apps148149Just as `httpx.Client` allows you to call directly into WSGI web applications,150the `httpx.AsyncClient` class allows you to call directly into ASGI web applications.151152Let's take this Starlette application as an example:153154```python155from starlette.applications import Starlette156from starlette.responses import HTMLResponse157from starlette.routing import Route158159160async def hello():161 return HTMLResponse("Hello World!")162163164app = Starlette(routes=[Route("/", hello)])165```166167We can make requests directly against the application, like so:168169```python170>>> import httpx

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

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

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 173–188why, one step back
173... assert r.status_code == 200
174... assert r.text == "Hello World!"175```176177For some more complex cases you might need to customise the ASGI dispatch. This allows you to:178179* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.180* Mount the ASGI application at a subpath by setting `root_path`.181* Use a given client address for requests by setting `client`.182183For example:184185```python186# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",187# on port 123.188dispatch = httpx.ASGIDispatch(app=app, client=("1.2.3.4", 123))

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

line 189why, one step back
189async with httpx.AsyncClient(dispatch=dispatch, base_url="http://testserver") as client:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 190–210why, one step back
190 ...
191```192193See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.194195## Unix Domain Sockets196197The 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.198199Here's an example requesting the Docker Engine API:200201```python202import httpx203204205async with httpx.AsyncClient(uds="/var/run/docker.sock") as client:206 # This request will connect through the socket file.207 resp = await client.get("http://localhost/version")208```209210This functionality is not currently available in the synchronous client.