# Example 2: asynchronous requests
import asyncio
import aiohttp
import time
import concurrent.futures
no = int(input("time of per "))
num_requests = int(input("enter the no of threads "))
no_1 = no
avg = 0
async def fetch():
async with aiohttp.ClientSession() as session:
await session.get('http://google.com')
while no > 0:
start = time.time()
async def main():
with concurrent.futures.ThreadPoolExecutor(max_workers=num_requests) as executor:
loop = asyncio.get_event_loop()
futures = [
loop.run_in_executor(
executor,
fetch
)
for i in range(num_requests)
]
for response in await asyncio.gather(*futures):
pass
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
temp = (time.time()-start)
print(temp)
avg = avg + temp
no = no - 1
print("Average is ",avg/no_1)
错误是RuntimeWarning:coroutine' fetch'从未等待过 handle = None#发生异常时需要中断循环。 虽然我在fetch函数中使用await
答案 0 :(得分:8)
fetch
包含 await
,但没有人等待fetch()
本身。相反,它由run_in_executor
调用,它是为同步函数设计的。虽然你当然可以像同步函数一样调用异步函数,但除非由协程等待或提交给事件循环,否则它将无效,并且问题中的代码都没有。
此外,不允许从其他线程调用asyncio协程,也不必这样做。如果您需要同时运行#{1}}"和#34;等协同程序,请使用fetch()
将它们提交到正在运行的循环中,并使用{{1}等待它们 en mass (你几乎已经在做了)。例如:
create_task()
可以在问题中调用 gather
:
async def main():
loop = asyncio.get_event_loop()
tasks = [loop.create_task(fetch())
for i in range(num_requests)]
for response in await asyncio.gather(*tasks):
pass # do something with response
但是,为时序代码创建一个协程并且仅调用main()
一次会更加惯用:
loop = asyncio.get_event_loop()
while no > 0:
start = time.time()
loop.run_until_complete(main())
...
no = no - 1
最后,您可能希望在loop.run_until_complete()
或async def avg_time():
while no > 0:
start = time.time()
await main()
...
no = no - 1
loop = asyncio.get_event_loop()
loop.run_until_complete(avg_time())
中创建ClientSession
,并将相同的会话对象传递给每个main
调用。会话通常在多个请求之间共享,并不是要为每个单独的请求重新创建。