Dev*_*n S 1 python asynchronous python-asyncio
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()
Run Code Online (Sandbox Code Playgroud)
api_request_list 应包含函数列表。该函数列表应传递到 asyncio.gather 中。
我目前收到以下错误消息:
RuntimeError: cannot reuse already awaited coroutine
Run Code Online (Sandbox Code Playgroud)
这不是函数列表。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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11897 次 |
| 最近记录: |