python – 如何确定给定port = 0时aiohttp选择哪个端口

当我使用aiohttp.web.run_app(…,port = 0)时,我假设它选择了一个可供服务的任意可用端口.它是否正确?如果是这样,是否有某种方法可以找出它所选择的端口?

解决方法:

您可以使用server.sockets,如下面的代码所示:

@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()
上一篇:python – 当新请求来自同一会话中的同一用户时,如何取消先前的请求


下一篇:使用aiohttp的时候提示python版本必须大于3.5.2 将ubuntu中的python3.5.2升级至python3.7