Aiohttp 为异步 Web 客户端和服务器实现提供了标准库。这里讨论 StreamReader 对象的三个方法:iter_chunked、iter_any 和 iter_chunks。
这些方法的共同点是:它们都是用来从流中读取数据的。不同之处在于读取流的方式。下面分别介绍这三种方式:
async def read_stream(reader):
while True:
chunk = await reader.read_chunk() # 等同于 await reader.read() + chunk_size 的格式
if not chunk:
break
print(chunk)
async with aiohttp.ClientSession() as session:
async with session.get('http://example.com') as resp:
stream_reader = resp.content
await read_stream(stream_reader)
async def read_stream(reader):
while True:
chunk = await reader.read() # 返回所有的可用数据
if not chunk:
break
print(chunk)
async with aiohttp.ClientSession() as session:
async with session.get('http://example.com') as resp:
stream_reader = resp.content
await read_stream(stream_reader)
async def read_stream(reader):
async for chunk in reader.iter_chunked(chunk_size=1024):
print(chunk)
async with aiohttp.ClientSession() as session:
async with session.get('http://example.com') as resp:
stream_reader = resp.content
await read_stream(stream_reader)