async.md
This file
Path
docs/async.md
59 lines · 1.6 KiB · Markdown
Last changed by
Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970
History of this fileTake it
http3 (#86)Tom Christiebefore adoptionc9747aa
lines 1–9why, 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.9Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970
lines 10–11why, one step back10If you're working with an async web framework then you'll also want to use an11async client for sending outgoing HTTP requests.http3 (#86)Tom Christiebefore adoptionc9747aa
lines 12–59why, one step back1213## Making Async requests1415To make asynchronous requests, you'll need an `AsyncClient`.1617```python18>>> client = http3.AsyncClient()19>>> r = await client.get('https://www.example.com/')20```2122## API Differences2324If you're using streaming responses then there are a few bits of API that25use async methods:2627```python28>>> client = http3.AsyncClient()29>>> r = await client.get('https://www.example.com/', stream=True)30>>> try:31>>> async for chunk in r.stream():32>>> ...33>>> finally:34>>> await r.close()35```3637The async response methods are:3839* `.read()`40* `.stream()`41* `.raw()`42* `.close()`4344If you're making parallel requests, then you'll also need to use an async API:4546```python47>>> client = http3.AsyncClient()48>>> async with client.parallel() as parallel:49>>> pending_one = parallel.get('https://example.com/1')50>>> pending_two = parallel.get('https://example.com/2')51>>> response_one = await pending_one.get_response()52>>> response_two = await pending_two.get_response()53```5455The async parallel methods are:5657* `.parallel()` *Used as an "async with" context manager.*58* `.get_response()`59* `.next_response()`