0

There are two things need to be done: host website and send notification.So I use the following ways to solve this problems:

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()

Because there is one event_loop in web.run_app, I don't understand which one run first and how to control every event_loop.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
andy
  • 1,951
  • 5
  • 16
  • 30

1 Answers1

0

Your way to create a task before starting event loop is ok, but only if run_app won't set and use another event loop.

Better way is to create tasks or other async objects once event loop is started. This way you will make sure created objects are attached to an active running event loop.

The best way to do it in your case is to use on_startup hook:

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())
Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159
  • in this way, I will send message first then I can open website. In my way I can open website and send message at the same time. If I add await asyncio.sleep(20) in pre_init function I can control when to send message after open website. But in your way I must wait 20 seconds then open website – andy Mar 04 '20 at 07:43
  • I tried, same result. Maybe I didn't speak my mind clearly – andy Mar 04 '20 at 08:46
  • Maybe the OP wants `asyncio.create_task(_send_proactive_message)` in `pre_init` instead of `await ...`? – user4815162342 Mar 04 '20 at 10:17
  • maybe all this due to my python version is 3.6? – andy Mar 04 '20 at 11:30