How to determine which port aiohttp selects when given port=0

Question:

When I use aiohttp.web.run_app(. . ., port=0), I assume that it selects an arbitrary available port on which to serve. Is this correct? And if so, is there some way to figure out what port it’s selected?

Asked By: abingham

||

Answers:

You use server.sockets as in the following code:

@asyncio.coroutine
def status(request):
    """Check that the app is properly working"""
    return web.json_response('OK')


app = web.Application()  # pylint: disable=invalid-name
app.router.add_get('/api/status', status)


def main():
    """Starts the aiohttp process to serve the REST API"""
    loop = asyncio.get_event_loop()
     # continue server bootstraping
    handler = app.make_handler()
    coroutine = loop.create_server(handler, '0.0.0.0', 0)
    server = loop.run_until_complete(coroutine)
    print('Serving on http://%s:%s' % server.sockets[0].getsockname()) # HERE!
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.close()
        loop.run_until_complete(server.wait_closed())
        loop.run_until_complete(handler.finish_connections(1.0))
        loop.close()
Answered By: amirouche

When using application runners, you can pass in port 0 and access the selected port via the site object:

runner = web.AppRunner(app)
await runner.setup()

site = web.TCPSite(runner, 'localhost', 0)
await site.start()

print('Serving on http://%s:%s' % site._server.sockets[0].getsockname())
Answered By: Albert Peschar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.