简体   繁体   中英

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

I have written a small api wrapper and i wanted to try to put it in a discord bot using discord.py. I tried using requests, grequests and aiohttp for the requests, but that didn't work. The code that is throwing the error is the following:

async def _get(url):
    return await requests.get(url)

def getUser(name):
    url = 'some url'
    resp = asyncio.run(_get(url))

and the error is:

/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

this seems to be an issue just when using discord py, as the actual code works fine in python

requests.get() isn't asynchronous, so awaiting it is useless. However _get is, so to invoke it, you'd need to await it.

But requests.get is blocking, putting it in an async function won't solve the issue (at least I believe).
To work with API , you can use 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)

If you don't want getUser to be asynchronous, you can use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM