如何解决为什么我会收到 RuntimeWarning: Enable tracemalloc to get the object allocation traceback from asyncio.run?
我写了一个小的 api 包装器,我想尝试使用 discord.py 将它放入一个不和谐的机器人中。我尝试对请求使用请求、grequests 和 aiohttp,但这没有用。抛出错误的代码如下:
async def _get(url):
return await requests.get(url)
def getUser(name):
url = 'some url'
resp = asyncio.run(_get(url))
错误是:
/usr/lib/python3.8/asyncio/events.py:81: RuntimeWarning: coroutine '_get' was never awaited
self._context.run(self._callback,*self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
这似乎是使用 discord py 时的问题,因为实际代码在 python 中运行良好
解决方法
requests.get()
不是异步的,所以等待它是没有用的。但是 _get
是,因此要调用它,您需要 await
它。
但是 requests.get
是阻塞的,将它放在 async
函数中并不能解决问题(至少我相信)。
要使用 API
,您可以使用 aiohttp
:
# Set json to True if the response uses json format
async def _get(link,headers=None,json=False):
async with ClientSession() as s:
async with s.get(link,headers=headers) as resp:
return await resp.json() if json else await resp.text()
async def getUser(name):
url = 'some url'
resp = await _get(url)
如果您不希望 getUser
是异步的,您可以使用 asyncio.run_coroutine_threadsafe
:
from asyncio import run_coroutine_threadsafe
def getUser(name):
url = 'some url'
resp = run_coroutine_threadsafe(_get(url),bot.loop) #or client.loop
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。