parallel.md
This file
Path
docs/parallel.md
66 lines · 2.2 KiB · Markdown
Last changed by
http3 (#86)Tom Christiebefore adoptionc9747aa
History of this fileTake it
http3 (#86)Tom Christiebefore adoptionc9747aa
lines 1–66why, one step back1# Parallel Requests23HTTP3 allows you to make HTTP requests in parallel in a highly efficient way,4using async under the hood, while still presenting a standard threaded interface.56This has the huge benefit of allowing you to efficiently make parallel HTTP7requests without having to switch out to using async all the way through.89## Making Parallel Requests1011Let's make two outgoing HTTP requests in parallel:1213```python14>>> with http3.parallel() as parallel:15>>> pending_one = parallel.get('https://example.com/1')16>>> pending_two = parallel.get('https://example.com/2')17>>> response_one = pending_one.get_response()18>>> response_two = pending_two.get_response()19```2021If we're making lots of outgoing requests, we might not want to deal with the22responses sequentially, but rather deal with each response that comes back23as soon as it's available:2425```python26>>> with http3.parallel() as parallel:27>>> for counter in range(1, 10):28>>> parallel.get(f'https://example.com/{counter}')29>>> while parallel.has_pending_responses:30>>> r = parallel.next_response()31```3233## Exceptions and Cancellations3435The style of using `parallel` blocks ensures that you'll always have well36defined exception and cancellation behaviours. Request exceptions are only ever37raised when calling either `get_response` or `next_response`, and any pending38requests are cancelled on exiting the block.3940## Parallel requests with a Client4142You can also call `parallel()` from a client instance, which allows you to43control the authentication or dispatch behaviour for all requests within the44block.4546```python47>>> client = http3.Client()48>>> with client.parallel() as parallel:49>>> ...50```5152## Async parallel requests5354If you're working within an async framework, then you'll want to use a fully55async API for making requests.5657```python58>>> client = http3.AsyncClient()59>>> async with client.parallel() as parallel:60>>> pending_one = await parallel.get('https://example.com/1')61>>> pending_two = await parallel.get('https://example.com/2')62>>> response_one = await pending_one.get_response()63>>> response_two = await pending_two.get_response()64```6566See [the Async Client documentation](async.md) for more details.