How can aiohttp server close itself?

476 views
Skip to first unread message

shais...@yahoo.co.uk

unread,
Jun 10, 2018, 12:05:59 PM6/10/18
to aio-libs
I have a simple server, where one of the request handlers should make the server close itself:

from aiohttp import web

async
def close_server(request):
   
# what to do here to make the server close itself?
   
return web.Response(text="Closing server bye bye")
   
app
= web.Application()
app
.add_routes([web.get('/close-server', close_server)])
web
.run_app(app)



Looking at the aiohttp documentation I have not found how to do this.

Thanks,

Shai

Andrew Svetlov

unread,
Jun 10, 2018, 3:11:40 PM6/10/18
to aio-libs
`web.run_app` is a shortcut for runer interface: https://docs.aiohttp.org/en/stable/web_advanced.html#application-runners

Calling `runner.cleanup()` closes the server. 

Shai Shasag

unread,
Jun 11, 2018, 4:20:45 AM6/11/18
to aio-libs
Andrew,

web.run_app maybe a shortcut, but it does a lot and I would not want to loose all the good functionality there: multiple sites, ssl_context, logging, etc.
Writing my own code meas to reconstruct all that functionality, just to get the runner instance so later I might call cleanup().

I tried a different approach:
At the point where the code decides to exit I did all the cleanups and called:

raise GracefulExit()

The server quits with exit code 0, but it does print the stack trace.

What do you think?

Thanks,

Shai

Andrew Svetlov

unread,
Jun 11, 2018, 6:19:26 AM6/11/18
to aio-libs

Application runner supports multiple sites and ssl context.
In real application you most likely need to more complex logging setup than `run_app` does: install custom log handlers to store logs in logstash/sentry, rotating log files etc.

If GracefulExit works for you -- that's nice, but the main intention of `run_app` is easy start on local development box, not using in production.
Reply all
Reply to author
Forward
0 new messages