我正在創建一個對外部 API 進行多次呼叫的專案。這些 API 呼叫是在類實體的方法中進行的。我正在嘗試制作一個通用函式,它接受這些物件的可迭代并為它們生成一個異步迭代器。然后,此異步迭代器將用于使所有這些外部 API 呼叫異步運行。
但是,根據我在下面的嘗試,執行時間仍然隨著串列的長度線性增加。
async def async_iterator(iterable: Iterable[Any]) -> AsyncIterator[Any]:
for i in iterable:
yield i
async for object in async_generator(iterable=list_of_objects):
await object.make_time_consuming_api_call()
# do other work on the object
await update_in_database(object=object)
如何異步迭代任何物件串列?
uj5u.com熱心網友回復:
由于您正在等待object.make_time_consuming_api_call(),因此它會等待每個呼叫完成,然后才能運行下一次迭代。在提交所有呼叫后,您可以稍后等待它asyncio.create_task:
async def async_iterator(iterable: Iterable[Any]) -> AsyncIterator[Any]:
for i in iterable:
yield i
async def main():
tasks = list()
async for object in async_generator(iterable=list_of_objects):
tasks.append(asyncio.create_task(object.make_time_consuming_api_call()))
# do other work on the object
for task, object in zip(tasks, list_of_objects):
await task
await update_in_database(object=object)
在這種情況下,您甚至不需要創建async_iterator:
async def main():
tasks = list()
for object in list_of_objects:
tasks.append(asyncio.create_task(object.make_time_consuming_api_call()))
或者讓它更簡潔:
async def main():
results = await asyncio.gather(*(object.make_time_consuming_api_call() for object in list_of_objects))
# Added this to store the result as an attribute (see comments)
for result, object in zip(results, list_of_objects):
object.attribute = result
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/459252.html
下一篇:為什么一個代表比另一個快?
