Skip to content
Myr

async.md

This file

Path

docs/async.md

59 lines · 1.6 KiB · Markdown

Last changed by

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

History of this file

Take it

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 1–2why, one step back
1# Async Client
2

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 3why, one step back
3HTTPX offers a standard synchronous API by default, but also gives you

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 4–9why, one step back
4the 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.9

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

lines 10–11why, one step back
10If you're working with an async web framework then you'll also want to use an
11async client for sending outgoing HTTP requests.

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 12–17why, one step back
12
13## Making Async requests1415To make asynchronous requests, you'll need an `AsyncClient`.1617```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 18why, one step back
18>>> client = httpx.AsyncClient()

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 19–27why, one step back
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```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 28why, one step back
28>>> client = httpx.AsyncClient()

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 29–46why, one step back
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```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 47why, one step back
47>>> client = httpx.AsyncClient()

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 48–59why, one step back
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()`