为什么我收到 RuntimeWarning: E​​nable tracemalloc to get the object allocation traceback from asyncio.run?

Why am i getting RuntimeWarning: Enable tracemalloc to get the object allocation traceback from asyncio.run?

我写了一个小的 api 包装器,我想尝试使用 discord.py 将它放入 discord 机器人中。我尝试对请求使用请求、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