From 1ebeec4996ecb724eb6248aad2d50ad2867c1bc3 Mon Sep 17 00:00:00 2001 From: Rodja Trappe Date: Sun, 27 Aug 2023 09:13:19 +0200 Subject: [PATCH] catch gaierror and improve startup speed --- nicegui/nicegui.py | 2 +- nicegui/welcome.py | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/nicegui/nicegui.py b/nicegui/nicegui.py index 8297abdb9..81ec5e41a 100644 --- a/nicegui/nicegui.py +++ b/nicegui/nicegui.py @@ -93,7 +93,7 @@ def handle_startup(with_welcome_message: bool = True) -> None: background_tasks.create(prune_slot_stacks()) globals.state = globals.State.STARTED if with_welcome_message: - welcome.print_message() + background_tasks.create(welcome.print_message()) if globals.air: background_tasks.create(globals.air.connect()) diff --git a/nicegui/welcome.py b/nicegui/welcome.py index b54546687..0790b3320 100644 --- a/nicegui/welcome.py +++ b/nicegui/welcome.py @@ -1,3 +1,4 @@ +import asyncio import os import socket from typing import List @@ -13,7 +14,11 @@ def get_all_ips() -> List[str]: if 'netifaces' not in globals.optional_features: - return [info[4][0] for info in socket.getaddrinfo(socket.gethostname(), None) if len(info[4]) == 2] + try: + hostname = socket.gethostname() + return socket.gethostbyname_ex(hostname)[2] + except socket.gaierror: + return [] ips = [] for interface in netifaces.interfaces(): try: @@ -23,12 +28,17 @@ def get_all_ips() -> List[str]: return ips -def print_message() -> None: +async def print_message() -> None: + print('NiceGUI ready to go ', end='', flush=True) host = os.environ['NICEGUI_HOST'] port = os.environ['NICEGUI_PORT'] - ips = set(get_all_ips() if host == '0.0.0.0' else []) + loop = asyncio.get_running_loop() + ips = set((await loop.run_in_executor(None, get_all_ips)) if host == '0.0.0.0' else []) ips.discard('127.0.0.1') addresses = [(f'http://{ip}:{port}' if port != '80' else f'http://{ip}') for ip in ['localhost'] + sorted(ips)] if len(addresses) >= 2: addresses[-1] = 'and ' + addresses[-1] - print(f'NiceGUI ready to go on {", ".join(addresses)}', flush=True) + extra = '' + if 'netifaces' not in globals.optional_features: + extra = ' (install netifaces to show all IPs and speedup this message)' + print(f'on {", ".join(addresses)}' + extra, flush=True)