簡體   English   中英

為什么我會收到 RuntimeWarning: Enable 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 機器人中。 我嘗試對請求使用 requests、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 function 不會解決問題(至少我相信)。
要使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM