Skip to content
Myr

async.md

This file

Path

docs/async.md

204 lines · 6.5 KiB · Markdown

Last changed by

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

History of this file

Take it

The walk stopped after 200 commits: lines older than 66a4537 point at it.

Add mypy config for tests directory (#991)Florimond Mancabefore adoption66a4537

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

Add mypy config for tests directory (#991)Florimond Mancabefore adoption66a4537

lines 18–66why, one step back
18>>> 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.66

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

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

Add mypy config for tests directory (#991)Florimond Mancabefore adoption66a4537

lines 68–80why, one step back
68>>> client = httpx.AsyncClient()
69>>> async with client.stream('GET', 'https://www.example.com/') as response:70>>> async for chunk in response.aiter_bytes():71>>> ...72```7374The async response streaming methods are:7576* `Response.aread()` - For conditionally reading a response inside a stream block.77* `Response.aiter_bytes()` - For streaming the response content as bytes.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.

Add "manual streaming mode" docs (#1046)Florimond Mancabefore adoptiondf24a0f

lines 81–101why, one step back
81* `Response.aclose()` - For closing the response. You don't usually need this, since `.stream` block closes the response automatically on exit.
8283For 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)`.8485Example in the context of forwarding the response to a streaming web endpoint with [Starlette](https://www.starlette.io):8687```python88import httpx89from starlette.background import BackgroundTask90from starlette.responses import StreamingResponse9192client = httpx.AsyncClient()9394async def home(request):95 req = client.build_request("GET", "https://www.example.com/")96 r = await client.send(req, stream=True)97 return StreamingResponse(r.aiter_text(), background=BackgroundTask(r.aclose))98```99100!!! warning101 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.

Add mypy config for tests directory (#991)Florimond Mancabefore adoption66a4537

lines 102–179why, one step back
102
103### Streaming requests104105When sending a streaming request body with an `AsyncClient` instance, you should use an async bytes generator instead of a bytes generator:106107```python108async def upload_bytes():109 ... # yield byte content110111await client.post(url, data=upload_bytes())112```113114## Supported async environments115116HTTPX supports either `asyncio` or `trio` as an async environment.117118It will auto-detect which of those two to use as the backend119for socket operations and concurrency primitives.120121### [AsyncIO](https://docs.python.org/3/library/asyncio.html)122123AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)124for writing concurrent code with the async/await syntax.125126```python127import asyncio128import httpx129130async def main():131 async with httpx.AsyncClient() as client:132 response = await client.get('https://www.example.com/')133 print(response)134135asyncio.run(main())136```137138### [Trio](https://github.com/python-trio/trio)139140Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),141designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).142143```python144import httpx145import trio146147async def main():148 async with httpx.AsyncClient() as client:149 response = await client.get('https://www.example.com/')150 print(response)151152trio.run(main)153```154155!!! important156 The `trio` package must be installed to use the Trio backend.157158## Calling into Python Web Apps159160Just as `httpx.Client` allows you to call directly into WSGI web applications,161the `httpx.AsyncClient` class allows you to call directly into ASGI web applications.162163Let's take this Starlette application as an example:164165```python166from starlette.applications import Starlette167from starlette.responses import HTMLResponse168from starlette.routing import Route169170171async def hello():172 return HTMLResponse("Hello World!")173174175app = Starlette(routes=[Route("/", hello)])176```177178We can make requests directly against the application, like so:179

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

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

Add mypy config for tests directory (#991)Florimond Mancabefore adoption66a4537

lines 181–204why, one step back
181>>> import httpx
182>>> async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:183... r = await client.get("/")184... assert r.status_code == 200185... assert r.text == "Hello World!"186```187188For some more complex cases you might need to customise the ASGI transport. This allows you to:189190* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.191* Mount the ASGI application at a subpath by setting `root_path`.192* Use a given client address for requests by setting `client`.193194For example:195196```python197# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",198# on port 123.199transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))200async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:201 ...202```203204See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.