async.md
This file
Path
docs/async.md
205 lines · 6.5 KiB · Markdown
Last changed by
fix code example, in async.md (#1388)podhmobefore adoptionf8f5430
History of this fileTake it
The walk stopped after 200 commits: lines older than 56d8800 point at it.
Version 0.13.3 (#1006)Tom Christiebefore adoption56d8800
lines 1–16why, one step back1# Async Support23HTTPX 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`.16Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 17why, one step back17```pyconVersion 0.13.3 (#1006)Tom Christiebefore adoption56d8800
line 18why, one step back18>>> async with httpx.AsyncClient() as client:Fix typo (#1386)Kyungmin Leebefore adoption84dca25
lines 19–20why, one step back19... r = await client.get('https://www.example.com/')20...Version 0.13.3 (#1006)Tom Christiebefore adoption56d8800
lines 21–67why, one step back21>>> 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```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.67Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 68why, one step back68```pyconVersion 0.13.3 (#1006)Tom Christiebefore adoption56d8800
lines 69–70why, one step back69>>> 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 back71... async for chunk in response.aiter_bytes():72... ...Version 0.13.3 (#1006)Tom Christiebefore adoption56d8800
lines 73–81why, one step back73```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.Add "manual streaming mode" docs (#1046)Florimond Mancabefore adoptiondf24a0f
lines 82–102why, one step back82* `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.Version 0.13.3 (#1006)Tom Christiebefore adoption56d8800
lines 103–171why, one step back103104### 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```114115## Supported async environments116117HTTPX supports either `asyncio` or `trio` as an async environment.118119It will auto-detect which of those two to use as the backend120for socket operations and concurrency primitives.121122### [AsyncIO](https://docs.python.org/3/library/asyncio.html)123124AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)125for writing concurrent code with the async/await syntax.126127```python128import asyncio129import httpx130131async def main():132 async with httpx.AsyncClient() as client:133 response = await client.get('https://www.example.com/')134 print(response)135136asyncio.run(main())137```138139### [Trio](https://github.com/python-trio/trio)140141Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),142designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).143144```python145import httpx146import trio147148async def main():149 async with httpx.AsyncClient() as client:150 response = await client.get('https://www.example.com/')151 print(response)152153trio.run(main)154```155156!!! important157 The `trio` package must be installed to use the Trio backend.158159## Calling into Python Web Apps160161Just as `httpx.Client` allows you to call directly into WSGI web applications,162the `httpx.AsyncClient` class allows you to call directly into ASGI web applications.163164Let's take this Starlette application as an example:165166```python167from starlette.applications import Starlette168from starlette.responses import HTMLResponse169from starlette.routing import Route170171fix code example, in async.md (#1388)podhmobefore adoptionf8f5430
line 172why, one step back172async def hello(request):Version 0.13.3 (#1006)Tom Christiebefore adoption56d8800
lines 173–180why, one step back173 return HTMLResponse("Hello World!")174175176app = Starlette(routes=[Route("/", hello)])177```178179We can make requests directly against the application, like so:180Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 181why, one step back181```pyconVersion 0.13.3 (#1006)Tom Christiebefore adoption56d8800
lines 182–205why, one step back182>>> import httpx183>>> async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:184... r = await client.get("/")185... assert r.status_code == 200186... assert r.text == "Hello World!"187```188189For some more complex cases you might need to customise the ASGI transport. This allows you to:190191* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.192* Mount the ASGI application at a subpath by setting `root_path`.193* Use a given client address for requests by setting `client`.194195For example:196197```python198# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",199# on port 123.200transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))201async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:202 ...203```204205See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.