如何在循环中等待方法?

5 python asynchronous async-await python-asyncio aiohttp

我有以下方法为我生成数据:

async def generate_url(self, video_id):
    data = await self.s3.generate_presigned_url(...video_id...)
    return data

def convert_to_json(self, urls):
    ids = [self.generate_url(url) for url in urls]
    ...
Run Code Online (Sandbox Code Playgroud)

如何正确地等待generate_urlconvert_to_json

VMA*_*Atm 8

您可以wait在任务列表周围使用包装器:

async def convert_to_json(self, urls):
    tasks = [self.generate_url(url) for url in urls]
    await asyncio.wait(tasks)
Run Code Online (Sandbox Code Playgroud)

或者,如果您无法将convert_to_json方法标记为async,请同步等待:

import asyncio

def convert_to_json(self, urls):
    loop = asyncio.get_event_loop()
    tasks = [self.generate_url(url) for url in urls]
    loop.run_until_complete(asyncio.wait(tasks))
Run Code Online (Sandbox Code Playgroud)

你也可以尝试实现一个async迭代器,并使用它async for的语法,是这样的:

class Loader:
    def __init__(self, urls):
        self._urls = iter(urls)

    async def generate_url(self, video_id):
        data = await self.s3.generate_presigned_url(...video_id...)
        return data

    def __aiter__(self):
        return self

    async def __anext__(self):
        try:
            url = next(self._urls)
        except StopIteration:
            raise StopAsyncIteration
        data = await self.generate_url(url)
        return data

async for id in Loader(urls):
    print(id)
Run Code Online (Sandbox Code Playgroud)