python-3.x - 为什么我们在发送异步请求时需要使用 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
解决方案
我认为这个问题的答案植根于设计模式。上下文管理器(同步和异步)的情况与“控制反转”和“依赖注入”有关。它提供了一种系统统一的资源管理方式(在异步的情况下封装在各种promise对象中)
当然,您所寻求的模式可以通过在各种库已经提供的内容之上编写您自己的抽象来构建。
推荐阅读
- powershell - Why behave a replace function differently in module or script?
- swift - 如何在“UIKit for Mac”平台上使用 SwiftUI 打开文件对话框?
- php - 无法将 CSV 文件导入 SQL(使用 PDO)
- python - 如何使用 vgg-19 预测单张图像?
- python - Get the corresponding sums of parts of a list
- angular - 角度 json web 令牌 x-auth-token 未使用 intreceptor 正确保存
- javascript - CSS 应该包含在 NPM 组件库中还是手动加载?
- node.js - 在两个 NodeJS 进程之间发送消息的最简单和最快的方法是什么?
- php - 表单回显不适用于列表中的第一项
- rest - 包含 POST 和 PUT/PATCH 的 REST API 调用计算服务器生成结果文件