【发布时间】:2017-08-09 20:48:22
【问题描述】:
我正在尝试编写一个不和谐的机器人,用我从 http rest 调用中获取的数据更新用户。
由于 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 和异步函数很陌生。
【问题讨论】:
标签: python multithreading python-3.x python-asyncio