为什么它说从未等待过FETCH函数? [英] Why it says fetch function was never awaited?

查看:23
本文介绍了为什么它说从未等待过FETCH函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行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包含ANawait,但没有人在等待fetch()本身。相反,它是由run_in_executor调用的,run_in_executor是为同步函数设计的。虽然您当然可以调用与同步函数类似的异步函数,但除非由协程程序等待或提交给事件循环,否则它不会产生任何效果,而问题中的代码既不执行这两种操作,也不执行这两项操作。

此外,不允许从不同的线程调用异步协同例程,也没有必要这样做。如果您需要"并行"运行像fetch()这样的协同例程,请使用create_task()将它们提交到运行循环,并使用gather等待它们en mass(您几乎已经在这样做了)。例如:

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调用。会话通常在多个请求之间共享,不会为每个单独的请求重新创建。

这篇关于为什么它说从未等待过FETCH函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆