为什么它说从未等待过获取功能?

Why it says fetch function was never awaited?

我正在尝试执行 asynchronous requests 如下:

# 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' was never awaited
  handle = None  # Needed to break cycles when an exception occurs

即使我在 fetch 函数中使用 await。为什么会这样?

fetch确实包含一个await,但没有人在等待fetch()本身。相反,它由专为同步功能设计的 run_in_executor 调用。虽然您当然可以像调用同步函数一样调用异步函数,但除非协程等待或提交给事件循环,否则它不会有任何效果,而问题中的代码两者都不做。

此外,不允许从不同的线程调用异步协程,也没有必要这样做。如果您需要 运行 像 fetch() "in parallel" 这样的协程,请使用 create_task() 将它们提交到 运行ning 循环并等待它们 en mass 使用 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())

最后,您可能希望在 maineverything 中创建 ClientSession 并将相同的会话对象传递给每个 fetch 调用。会话通常在多个请求之间共享,并不意味着要为每个单独的请求重新创建。