Просмотр исходного кода

refine app listen address message

wangweimin 3 лет назад
Родитель
Сommit
f6fdde9d48

+ 2 - 2
pywebio/platform/aiohttp.py

@@ -11,7 +11,7 @@ from aiohttp import web
 
 
 from .remote_access import start_remote_access_service
 from .remote_access import start_remote_access_service
 from .tornado import open_webbrowser_on_server_started
 from .tornado import open_webbrowser_on_server_started
-from .utils import make_applications, render_page, cdn_validation, deserialize_binary_event
+from .utils import make_applications, render_page, cdn_validation, deserialize_binary_event, print_listen_address
 from ..session import CoroutineBasedSession, ThreadBasedSession, register_session_implement_for_target, Session
 from ..session import CoroutineBasedSession, ThreadBasedSession, register_session_implement_for_target, Session
 from ..session.base import get_session_info_from_headers
 from ..session.base import get_session_info_from_headers
 from ..utils import get_free_port, STATIC_PATH, iscoroutinefunction, isgeneratorfunction
 from ..utils import get_free_port, STATIC_PATH, iscoroutinefunction, isgeneratorfunction
@@ -205,7 +205,7 @@ def start_server(applications, port=0, host='', debug=False,
     if debug:
     if debug:
         logging.getLogger("asyncio").setLevel(logging.DEBUG)
         logging.getLogger("asyncio").setLevel(logging.DEBUG)
 
 
-    print('Listen on %s:%s' % (host, port))
+    print_listen_address(host, port)
 
 
     if remote_access:
     if remote_access:
         start_remote_access_service(local_port=port)
         start_remote_access_service(local_port=port)

+ 2 - 2
pywebio/platform/path_deploy.py

@@ -12,7 +12,7 @@ from . import utils
 from .httpbased import HttpHandler
 from .httpbased import HttpHandler
 from .tornado import webio_handler, set_ioloop
 from .tornado import webio_handler, set_ioloop
 from .tornado_http import TornadoHttpContext
 from .tornado_http import TornadoHttpContext
-from .utils import cdn_validation, make_applications
+from .utils import cdn_validation, make_applications, print_listen_address
 from ..session import register_session_implement, CoroutineBasedSession, ThreadBasedSession, Session
 from ..session import register_session_implement, CoroutineBasedSession, ThreadBasedSession, Session
 from ..utils import get_free_port, STATIC_PATH, parse_file_size
 from ..utils import get_free_port, STATIC_PATH, parse_file_size
 
 
@@ -209,7 +209,7 @@ def _path_deploy(base, port=0, host='', static_dir=None, cdn=True, max_payload_s
         handlers.append((r"/_pywebio_static/(.*)", StaticFileHandler, {"path": STATIC_PATH}))
         handlers.append((r"/_pywebio_static/(.*)", StaticFileHandler, {"path": STATIC_PATH}))
     handlers.append((r"/.*", RequestHandler))
     handlers.append((r"/.*", RequestHandler))
 
 
-    print('Listen on %s:%s' % (host or '0.0.0.0', port))
+    print_listen_address(host, port)
 
 
     set_ioloop(tornado.ioloop.IOLoop.current())  # to enable bokeh app
     set_ioloop(tornado.ioloop.IOLoop.current())  # to enable bokeh app
     app = tornado.web.Application(handlers=handlers, **tornado_app_settings)
     app = tornado.web.Application(handlers=handlers, **tornado_app_settings)

+ 2 - 2
pywebio/platform/tornado.py

@@ -18,7 +18,7 @@ from tornado.websocket import WebSocketHandler
 
 
 from . import utils
 from . import utils
 from .remote_access import start_remote_access_service
 from .remote_access import start_remote_access_service
-from .utils import make_applications, render_page, cdn_validation, deserialize_binary_event
+from .utils import make_applications, render_page, cdn_validation, deserialize_binary_event, print_listen_address
 from ..session import CoroutineBasedSession, ThreadBasedSession, ScriptModeSession, \
 from ..session import CoroutineBasedSession, ThreadBasedSession, ScriptModeSession, \
     register_session_implement_for_target, Session
     register_session_implement_for_target, Session
 from ..session.base import get_session_info_from_headers
 from ..session.base import get_session_info_from_headers
@@ -361,7 +361,7 @@ def start_server(applications, port=0, host='',
     _, port = _setup_server(webio_handler=handler, port=port, host=host, static_dir=static_dir,
     _, port = _setup_server(webio_handler=handler, port=port, host=host, static_dir=static_dir,
                             max_buffer_size=max_payload_size, **tornado_app_settings)
                             max_buffer_size=max_payload_size, **tornado_app_settings)
 
 
-    print('Listen on %s:%s' % (host or '0.0.0.0', port))
+    print_listen_address(host, port)
 
 
     if auto_open_webbrowser:
     if auto_open_webbrowser:
         tornado.ioloop.IOLoop.current().spawn_callback(open_webbrowser_on_server_started, host or 'localhost', port)
         tornado.ioloop.IOLoop.current().spawn_callback(open_webbrowser_on_server_started, host or 'localhost', port)

+ 2 - 2
pywebio/platform/tornado_http.py

@@ -9,7 +9,7 @@ from . import utils
 from ..session import Session
 from ..session import Session
 from .httpbased import HttpContext, HttpHandler
 from .httpbased import HttpContext, HttpHandler
 from .tornado import set_ioloop, _setup_server, open_webbrowser_on_server_started
 from .tornado import set_ioloop, _setup_server, open_webbrowser_on_server_started
-from .utils import cdn_validation
+from .utils import cdn_validation, print_listen_address
 from ..utils import parse_file_size
 from ..utils import parse_file_size
 
 
 logger = logging.getLogger(__name__)
 logger = logging.getLogger(__name__)
@@ -157,7 +157,7 @@ def start_server(applications, port=8080, host='',
     _, port = _setup_server(webio_handler=handler, port=port, host=host, static_dir=static_dir,
     _, port = _setup_server(webio_handler=handler, port=port, host=host, static_dir=static_dir,
                             max_buffer_size=parse_file_size(max_payload_size), **tornado_app_settings)
                             max_buffer_size=parse_file_size(max_payload_size), **tornado_app_settings)
 
 
-    print('Listen on %s:%s' % (host or '0.0.0.0', port))
+    print_listen_address(host, port)
     if auto_open_webbrowser:
     if auto_open_webbrowser:
         tornado.ioloop.IOLoop.current().spawn_callback(open_webbrowser_on_server_started, host or 'localhost', port)
         tornado.ioloop.IOLoop.current().spawn_callback(open_webbrowser_on_server_started, host or 'localhost', port)
 
 

+ 44 - 1
pywebio/platform/utils.py

@@ -1,14 +1,15 @@
 import fnmatch
 import fnmatch
 import json
 import json
+import socket
 import urllib.parse
 import urllib.parse
 from collections import defaultdict
 from collections import defaultdict
 from collections import namedtuple
 from collections import namedtuple
 from collections.abc import Mapping, Sequence
 from collections.abc import Mapping, Sequence
+from functools import lru_cache
 from functools import partial
 from functools import partial
 from os import path, environ
 from os import path, environ
 
 
 from tornado import template
 from tornado import template
-from functools import lru_cache
 
 
 from ..__version__ import __version__ as version
 from ..__version__ import __version__ as version
 from ..exceptions import PyWebIOWarning
 from ..exceptions import PyWebIOWarning
@@ -275,6 +276,48 @@ def deserialize_binary_event(data: bytes):
     return event
     return event
 
 
 
 
+def get_interface_ip(family: socket.AddressFamily) -> str:
+    """Get the IP address of an external interface. Used when binding to
+    0.0.0.0 or :: to show a more useful URL.
+
+    Copy from https://github.com/pallets/werkzeug/blob/df7492ab66aaced5eea964a58309caaadb1e8903/src/werkzeug/serving.py
+    Under BSD-3-Clause License
+    """
+    # arbitrary private address
+    host = "fd31:f903:5ab5:1::1" if family == socket.AF_INET6 else "10.253.155.219"
+
+    with socket.socket(family, socket.SOCK_DGRAM) as s:
+        try:
+            s.connect((host, 58162))
+        except OSError:
+            return "::1" if family == socket.AF_INET6 else "127.0.0.1"
+
+        return s.getsockname()[0]  # type: ignore
+
+
+def print_listen_address(host, port):
+    if not host:
+        host = '0.0.0.0'
+
+    all_address = False
+    if host == "0.0.0.0":
+        all_address = True
+        host = get_interface_ip(socket.AF_INET)
+    elif host == "::":
+        all_address = True
+        host = get_interface_ip(socket.AF_INET6)
+
+    if ':' in host:  # ipv6
+        host = '[%s]' % host
+
+    if all_address:
+        print('Running on all addresses.')
+        print('Use http://%s:%s/ to access the application' % (host, port))
+    else:
+        print('Running on http://%s:%s/' % (host, port))
+
+
+
 def seo(title, description=None, app=None):
 def seo(title, description=None, app=None):
     """Set the SEO information of the PyWebIO application (web page information provided when indexed by search engines)
     """Set the SEO information of the PyWebIO application (web page information provided when indexed by search engines)