Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - 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

question from:https://stackoverflow.com/questions/65934939/why-am-i-getting-runtimewarning-enable-tracemalloc-to-get-the-object-allocation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...