async.md
This file
Path
docs/async.md
60 lines · 1.6 KiB · Markdown
Last changed by
http3 (#86)Tom Christiebefore adoptionc9747aa
History of this fileTake it
http3 (#86)Tom Christiebefore adoptionc9747aa
lines 1–60why, one step back1# Async Client23HTTP3 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 such as Sanic, Starlette, FastAPI,11Responder or Bocadillo, then you'll also want to use an async client for sending12outgoing HTTP requests.1314## Making Async requests1516To make asynchronous requests, you'll need an `AsyncClient`.1718```python19>>> client = http3.AsyncClient()20>>> r = await client.get('https://www.example.com/')21```2223## API Differences2425If you're using streaming responses then there are a few bits of API that26use async methods:2728```python29>>> client = http3.AsyncClient()30>>> r = await client.get('https://www.example.com/', stream=True)31>>> try:32>>> async for chunk in r.stream():33>>> ...34>>> finally:35>>> await r.close()36```3738The async response methods are:3940* `.read()`41* `.stream()`42* `.raw()`43* `.close()`4445If you're making parallel requests, then you'll also need to use an async API:4647```python48>>> client = http3.AsyncClient()49>>> async with client.parallel() as parallel:50>>> pending_one = parallel.get('https://example.com/1')51>>> pending_two = parallel.get('https://example.com/2')52>>> response_one = await pending_one.get_response()53>>> response_two = await pending_two.get_response()54```5556The async parallel methods are:5758* `.parallel()` *Used as an "async with" context manager.*59* `.get_response()`60* `.next_response()`