【发布时间】:2019-11-27 16:58:11
【问题描述】:
我需要对多条数据发出 API 请求,然后处理每个结果。请求是分页的,所以我目前正在做
def get_results():
while True:
response = api(num_results=5)
if response is None: # No more results
break
yield response
def process_data():
for page in get_results():
for result in page:
do_stuff(result)
process_data()
我希望在处理当前结果时使用 asyncio 从 API 检索下一页结果,而不是等待结果,处理它们,然后再次等待。我已将代码修改为
import asyncio
async def get_results():
while True:
response = api(num_results=5)
if response is None: # No more results
break
yield response
async def process_data():
async for page in get_results():
for result in page:
do_stuff(result)
asyncio.run(process_data())
我不确定这是否符合我的预期。这是处理 API 结果的当前页面并异步获取下一页结果的正确方法吗?
【问题讨论】:
-
要使用 asyncio,您调用的 API 本身必须是异步的。一个好的指标是您必须等待它的结果。如果您的
async def函数中没有一个包含等待,则暗示它们并不是真正的异步。
标签: python python-asyncio