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
uj5u.com熱心網友回復:
那不是功能串列。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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432442.html
上一篇:如何將Task.Run(等待一些回傳位元組[]的異步函式)分配給變數
下一篇:異步函式的回傳型別
