首页 > 解决方案 > 为什么我们在发送异步请求时需要使用 Client 对象?

问题描述

同步发送请求的接口很简单:

# 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

标签: python-3.xasync-awaitpython-requestshttpx

解决方案


我认为这个问题的答案植根于设计模式。上下文管理器(同步和异步)的情况与“控制反转”和“依赖注入”有关。它提供了一种系统统一的资源管理方式(在异步的情况下封装在各种promise对象中)

当然,您所寻求的模式可以通过在各种库已经提供的内容之上编写您自己的抽象来构建。


推荐阅读