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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…