同步发送请求的接口很简单:
# using requests package
content = requests.get('http://www.example.com').content
# using httpx package:
content = httpx.get('http://www.example.com').content
但是,当异步发送请求时,它会变得有点复杂:
# using aiohttp package
async with aiohttp.ClientSession() as session:
async with session.get('http://www.example.org') as response:
content = await response.text()
# using httpx package
async with httpx.AsyncClient() as client:
response = await client.get('http://www.example.org')
content = response.content
为什么我们Client
在发送异步请求时必须使用这些对象?为什么接口不能像发送同步请求时那样简单:
# using imaginary package
response = await aiopackage.get('http://www.example.com')
content = response.content