带有nest_asyncio包的asyncio的异步/等待总是返回协程'get1'从未等待

Posted

技术标签:

【中文标题】带有nest_asyncio包的asyncio的异步/等待总是返回协程\'get1\'从未等待【英文标题】:Async/await of asyncio with nest_asyncio package is always returning coroutine 'get1' was never awaited带有nest_asyncio包的asyncio的异步/等待总是返回协程'get1'从未等待 【发布时间】:2020-12-09 18:58:30 【问题描述】:

嗨,伙计们,我正在使用带有 nest_asyncio 的 asyncio,但我总是得到从未等待过的协程

import asyncio
import tracemalloc
import aiohttp
import nest_asyncio
import json

tracemalloc.start()

async def request_call(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            assert response.status == 200
            data = await response.read()
            data = json.loads(data.decode("utf-8"))
            return data

def get_json(url):
    loop = asyncio.get_event_loop()
    nest_asyncio.apply(loop)
    result = loop.run_until_complete(request_call(url))
    return result

async def get2():
    url = "https://reqres.in/api/users?page=2"
    return get_json(url)

async def get1():
    return get2()

async def snap():
    return get1()

def data():
    result = asyncio.run(snap())
    print(result)

data()

输出:

async.py:37: RuntimeWarning: 协程 'get1' 从未等待 Data() 对象分配于(大多数 最近通话最后):文件“async.py”,lineno 31 返回get1()

我不明白是什么问题以及解决方法是什么?

Python=3.8.6 aiohttp=3.7.3 nest-asyncio=1.4.3

【问题讨论】:

【参考方案1】:

只需要在某些函数调用上添加等待

import asyncio
import tracemalloc
import aiohttp
import nest_asyncio
import json

tracemalloc.start()

async def request_call(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            assert response.status == 200
            data = await response.read()
            data = json.loads(data.decode("utf-8"))
            return data

def get_json(url):
    loop = asyncio.get_event_loop()
    nest_asyncio.apply(loop)
    result = loop.run_until_complete(request_call(url))
    return result

async def get2():
    url = "https://reqres.in/api/users?page=2"
    return get_json(url)

async def get1():
    return await get2()

async def snap():
    return await get1()

def data():
    result = asyncio.run(snap())
    print("AAAA")
    print(result)

data()

【讨论】:

以上是关于带有nest_asyncio包的asyncio的异步/等待总是返回协程'get1'从未等待的主要内容,如果未能解决你的问题,请参考以下文章

等效于带有工作“线程”的 asyncio.Queues

Asyncio:带有 aio-pika 的 Fastapi,消费者忽略 Await

带有 difflib 的 Python Asyncio 缓慢爬行

简单的 Python 多线程网络服务器,带有 Asyncio 和在主函数中调用的事件

在超时中包装 asyncio.gather

如何对可变参数模板函数的异构参数包进行通用计算?