welcome.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import os
  2. import socket
  3. from typing import List
  4. from . import globals # pylint: disable=redefined-builtin
  5. from .run_executor import io_bound
  6. try:
  7. import netifaces
  8. globals.optional_features.add('netifaces')
  9. except ImportError:
  10. pass
  11. def get_all_ips() -> List[str]:
  12. if 'netifaces' not in globals.optional_features:
  13. try:
  14. hostname = socket.gethostname()
  15. return socket.gethostbyname_ex(hostname)[2]
  16. except socket.gaierror:
  17. return []
  18. ips = []
  19. for interface in netifaces.interfaces(): # pylint: disable=c-extension-no-member
  20. try:
  21. ip = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr'] # pylint: disable=c-extension-no-member
  22. ips.append(ip)
  23. except KeyError:
  24. pass
  25. return ips
  26. async def print_message() -> None:
  27. print('NiceGUI ready to go ', end='', flush=True)
  28. host = os.environ['NICEGUI_HOST']
  29. port = os.environ['NICEGUI_PORT']
  30. ips = set((await io_bound(get_all_ips)) if host == '0.0.0.0' else [])
  31. ips.discard('127.0.0.1')
  32. urls = [(f'http://{ip}:{port}' if port != '80' else f'http://{ip}') for ip in ['localhost'] + sorted(ips)]
  33. globals.app.urls.update(urls)
  34. if len(urls) >= 2:
  35. urls[-1] = 'and ' + urls[-1]
  36. extra = ''
  37. if 'netifaces' not in globals.optional_features and os.environ.get('NO_NETIFACES', 'false').lower() != 'true':
  38. extra = ' (install netifaces to show all IPs and speedup this message)'
  39. print(f'on {", ".join(urls)}' + extra, flush=True)