将函数列表传递给 asyncio.gather()

Passing in a list of functions to asyncio.gather()

from aiohttp import ClientSession
import asyncio
import threading
import time     

 class Query():

    def execute_async(self):
    asyncio.run(self.call_requests())

    async def call_requests(self):
        self.api_request_list = []

        self.PROMETHEUS_URL = "http://www.randomnumberapi.com/api/v1.0/random?min=100&max=1000&count=1"

        self.api_request_list.append(self.api_request(self.PROMETHEUS_URL, 1))
        self.api_request_list.append(self.api_request(self.PROMETHEUS_URL, 1))
        self.api_request_list.append(self.api_request(self.PROMETHEUS_URL, 1))

        while True:
            timer_start = time.perf_counter()

            await asyncio.gather(*self.api_request_list)

            timer_stop = time.perf_counter()
            print(f"Performed all requests in... {timer_stop - timer_start:0.4f} seconds")

    async def api_request(self, query, sleep_duration):
        await asyncio.sleep(sleep_duration)
        async with ClientSession() as session:
            async with session.get(self.PROMETHEUS_URL) as response:
            response = await response.text()
            random_int = int(response[2])
            print('Request response... {0}'.format(random_int))

if __name__ == '__main__':
    query = Query()

api_request_list 应该包含一个函数列表。此函数列表应传递到 asyncio.gather.

我目前收到以下错误消息:

RuntimeError: cannot reuse already awaited coroutine

这不是函数列表。 asyncio.gather 不采用函数列表。

你所拥有的是 协程对象 的列表。调用 async 函数会生成一个协程对象,该对象保存异步函数调用的执行状态。

当您第二次将列表传递给 asyncio.gather 时,所有协程都已完成。你告诉 asyncio.gather“运行 这些协同程序”,而 asyncio.gather 告诉你“我不能那样做 - 它们已经 运行”。

如果你想再次运行一个异步函数,你需要再次调用它。您不能继续使用旧的协程对象。这意味着您需要在循环内填充列表:

while True:
    api_request_list = [
        self.api_request(self.PROMETHEUS_URL, 1),
        self.api_request(self.PROMETHEUS_URL, 1),
        self.api_request(self.PROMETHEUS_URL, 1),
    ]

    timer_start = time.perf_counter()

    await asyncio.gather(*api_request_list)

    timer_stop = time.perf_counter()
    print(f"Performed all requests in... {timer_stop - timer_start:0.4f} seconds")