Aiohttp: How to gracefully stop server programatically

Created on 23 Apr 2018  路  6Comments  路  Source: aio-libs/aiohttp

Long story short

I have a aiohtto-based service which has the main purpose to just perform a task running in the background. The http is here just to respond with health status of the background task. I don't see any way to programatically stop aiohttp server in case of exception raised by the task. The whole service should stop, because it doesn't make sense without healthy task. I tried something like this (the example is based on the aiohttp docs):

import logging
from aiohttp.web_runner import GracefulExit

log = logging.getLogger(__name__)

async def some_task(app):
    try:
        some_long_running_task()
    except asyncio.CancelledError:
        pass
    except Exception:
        log.exception('Some logs')
        raise GracefulExit()
    finally:
        await cleanup()

Expected behaviour

I'd expect aiohttp to run all the on_cleanup hooks. Or some documentation on how to programatically shutdown the service.

Actual behaviour

on_cleanup hooks are not called.

Steps to reproduce

Your environment