parallel.md
This file
Path
docs/parallel.md
71 lines · 2.4 KiB · Markdown
Last changed by
Docs tweaksTom Christiebefore adoption60dca3d
History of this fileTake it
http3 (#86)Tom Christiebefore adoptionc9747aa
lines 1–2why, one step back1# Parallel Requests2Docs tweaksTom Christiebefore adoption60dca3d
lines 3–7why, one step back3!!! warning4 This page documents some proposed functionality that is not yet released.5 See [pull request #52](https://github.com/encode/http3/pull/52) for the6 first-pass of an implementation.7http3 (#86)Tom Christiebefore adoptionc9747aa
lines 8–71why, one step back8HTTP3 allows you to make HTTP requests in parallel in a highly efficient way,9using async under the hood, while still presenting a standard threaded interface.1011This has the huge benefit of allowing you to efficiently make parallel HTTP12requests without having to switch out to using async all the way through.1314## Making Parallel Requests1516Let's make two outgoing HTTP requests in parallel:1718```python19>>> with http3.parallel() as parallel:20>>> pending_one = parallel.get('https://example.com/1')21>>> pending_two = parallel.get('https://example.com/2')22>>> response_one = pending_one.get_response()23>>> response_two = pending_two.get_response()24```2526If we're making lots of outgoing requests, we might not want to deal with the27responses sequentially, but rather deal with each response that comes back28as soon as it's available:2930```python31>>> with http3.parallel() as parallel:32>>> for counter in range(1, 10):33>>> parallel.get(f'https://example.com/{counter}')34>>> while parallel.has_pending_responses:35>>> r = parallel.next_response()36```3738## Exceptions and Cancellations3940The style of using `parallel` blocks ensures that you'll always have well41defined exception and cancellation behaviours. Request exceptions are only ever42raised when calling either `get_response` or `next_response`, and any pending43requests are cancelled on exiting the block.4445## Parallel requests with a Client4647You can also call `parallel()` from a client instance, which allows you to48control the authentication or dispatch behaviour for all requests within the49block.5051```python52>>> client = http3.Client()53>>> with client.parallel() as parallel:54>>> ...55```5657## Async parallel requests5859If you're working within an async framework, then you'll want to use a fully60async API for making requests.6162```python63>>> client = http3.AsyncClient()64>>> async with client.parallel() as parallel:65>>> pending_one = await parallel.get('https://example.com/1')66>>> pending_two = await parallel.get('https://example.com/2')67>>> response_one = await pending_one.get_response()68>>> response_two = await pending_two.get_response()69```7071See [the Async Client documentation](async.md) for more details.