0

大家好,我正在使用带有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()

输出 :

<coroutine object get1 at 0x0471AD28> async.py:37: RuntimeWarning: coroutine 'get1' is never awaited

我无法理解问题所在以及解决方法是什么?

Python=3.8.6 aiohttp=3.7.3 嵌套异步=1.4.3

4

1 回答 1

0

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

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()
于 2020-12-09T19:24:07.890 回答