aiohttp 是一个支持异步的 Python HTTP 客户端库,而 requests 是一个同步的库。它们之间有些差别。在读取响应内容时,使用 aiohttp 的 read 方法与使用 requests 的 iter_content 方法会有所不同。
使用 aiohttp 的 read 方法,可以直接获取整个响应内容,返回一个 bytes 对象。而使用 requests 的 iter_content 方法,则可以通过迭代每个数据块来获取响应内容。代码示例如下:
使用 aiohttp 的 read 方法:
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
data = await response.read()
print(data)
async def main():
async with aiohttp.ClientSession() as session:
await fetch(session, 'https://httpbin.org/get')
asyncio.run(main())
使用 requests 的 iter_content 方法:
import requests
response = requests.get('https://httpbin.org/get', stream=True)
for chunk in response.iter_content(chunk_size=1024):
print(chunk)