Yurii Rabeshko
Yurii Rabeshko

Reputation: 631

Signals don't work in aiohttp

I have simple asynchronous application written on aiohttp. I need to extend app instance on server startup or shutdown, but signals doesn't work at all (the function never executes):

from aiohttp import web

app = web.Application()

async def on_startup(app):
    app['key'] = "need to save something here"

app.on_startup.append(on_startup)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    srv = loop.run_until_complete(asyncio.gather(
        loop.create_server(app.make_handler(), host='0.0.0.0', port=8000)
    ))
    loop.run_forever()

How can I extend the app instance via callback? Does somebody have an idea?

P.S. I use stable aiohttp version (3.0.9).

Upvotes: 0

Views: 558

Answers (2)

Yurii Rabeshko
Yurii Rabeshko

Reputation: 631

I spend a time in search of solution... and I found it! I decide to explore the web.run_app() method to understand how it works. So, this method use AppRunner().setup() to configure application before it will be running. I'm not sure that it's the best solution, but it works :) Well, the final code looks like the following:

from aiohttp import web

app = web.Application()

async def on_startup(app):
    app['key'] = "need to save something here"

app.on_startup.append(on_startup)

# Create an instance of the application runner
runner = web.AppRunner(app, handle_signals=True)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    srv = loop.run_until_complete(asyncio.gather(
        runner.setup(),  # Configure the application before run the server
        loop.create_server(app.make_handler(), host='0.0.0.0', port=8000)
    ))
    loop.run_forever()

Upvotes: 1

SangminKim
SangminKim

Reputation: 9166

Try the below if there is no reason you should use low-level API like make_handler(), it will work with on_startup signal .

if __name__ == "__main__":
    web.run_app(app, host='0.0.0.0', port=8000)

run_app() will use the get_event_loop() internally for the loop it use.

Upvotes: 4

Related Questions