我编写了一个小型api包装器,我想尝试使用discord.py将它放在一个不和谐的机器人中。我试着使用请求、grequest和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在使用不和谐py时,这似乎是一个问题,因为实际代码在python中工作得很好。
发布于 2021-01-28 12:50:08
requests.get()是同步的,所以等待它是无用的,但是_get是。由于requests是同步的,所以您必须使用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.loophttps://stackoverflow.com/questions/65934939
复制相似问题