我正在嘗試編寫一個不和諧的機器人程序,它使用我從http休息調用中獲取的數據更新用戶。如何在asycio後臺線程中使用aiohttp
由於discord.py使用asyncio,我想我會嘗試按照這種方法。
async def my_background_task():
print("starting BG task")
await client.wait_until_ready()
while not client.is_closed:
requests.get(getMyUrl()).json()["dict_element"]
#do more stuff
client.loop.create_task(my_background_task())
client.run("api key goes here")
它使用同步「請求」庫足夠簡單。但是,我可以運行這個過程幾個小時,直到它崩潰。我假設因爲'請求'未能完成無限循環。
async def fetch(session, url):
async with session.get(url) as resp:
print(resp.status)
return await resp
async def fetch_url(loop, url):
async with aiohttp.ClientSession(loop=loop) as session:
await fetch(session, url)
async def my_method(url):
loop = asyncio.get_event_loop()
return loop.run_until_complete(fetch_url(loop,url))
async def my_background_task():
print("starting BG task")
await client.wait_until_ready()
while not client.is_closed:
await my_method.("www.theinternet.com/restcall").json()["dict_element"]
#do more stuff
所以我現在嘗試用aiohttp工作,但碰上這種循環中異步循環的問題。
我還沒有找到如何解決這個問題的正確解釋。我對Python和異步函數很陌生。