需要完成两件事:托管网站并发送通知。因此,我使用以下方法来解决此问题:
from aiohttp import web
import asyncio
async def _send_proactive_message():
...
async def pre_init():
await asyncio.sleep(20)
await _send_proactive_message()
APP = web.Application()
APP.router.add_post("/api/messages", messages)
APP.router.add_get("/api/notify", notify)
if __name__ == '__main__':
event_loop = asyncio.get_event_loop()
try:
event_loop.create_task(pre_init())
web.run_app(APP, host="localhost", port=CONFIG.PORT)
finally:
event_loop.close()
因为web.run_app中有一个event_loop,所以我不知道哪个先运行以及如何控制每个event_loop。请帮助我。
您可以在开始事件循环之前创建任务的方式是可行的,但前提是run_app
不会设置并使用另一个事件循环。
更好的方法是在事件循环开始后创建任务或其他异步对象。这样,您将确保创建的对象已附加到活动的运行事件循环中。
根据您的情况,最好的方法是使用on_startup钩子:
async def pre_init(app):
await _send_proactive_message()
async def make_app():
app = web.Application()
app.router.add_post("/api/messages", messages)
app.router.add_get("/api/notify", notify)
app.on_startup.append(pre_init)
return app
web.run_app(make_app())