与包的异步/等待nest_asyncio总是返回协程"get1"从未等待过



Hii伙计们,我正在使用带有nest_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()

输出:

<在0x0471AD28>async.py:37:运行时警告:协程"get1"从未等待过Data((对象分配时间(最多最近通话最后(:文件";"async.py";,第31行return get1((

我不明白问题出在哪里,修复方法是什么?

Python=3.8.6 aiohttp=3.7.3 nest asyncio=1.4.3

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

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()

相关内容

  • 没有找到相关文章

最新更新