From 9ab039a41a1d017b6524f61bf1c1a611103c70a5 Mon Sep 17 00:00:00 2001 From: Mirko Dietrich Date: Thu, 24 Oct 2024 19:02:00 +0200 Subject: [PATCH] feat: display web server URL in console when executing `run` command --- questionpy_sdk/webserver/app.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/questionpy_sdk/webserver/app.py b/questionpy_sdk/webserver/app.py index 2e95ed5f..f76f4012 100644 --- a/questionpy_sdk/webserver/app.py +++ b/questionpy_sdk/webserver/app.py @@ -56,6 +56,9 @@ class StateFilename(StrEnum): DEFAULT_STATE_STORAGE_PATH = Path(__file__).parent / "question_state_storage" +DEFAULT_STATE_STORAGE_PATH = Path(__file__).parent / "question_state_storage" +LEN_AF_INET = 2 +LEN_AF_INET6 = 4 class WebServer: @@ -84,6 +87,7 @@ async def start_server(self) -> None: self._runner = web.AppRunner(self._web_app) await self._runner.setup() await web.TCPSite(self._runner, self._host, self._port).start() + self._print_urls() async def stop_server(self) -> None: if self._runner: @@ -143,6 +147,25 @@ def _package_state_dir(self) -> Path: manifest = self._web_app[MANIFEST_APP_KEY] return self._state_storage_root / f"{manifest.namespace}-{manifest.short_name}-{manifest.version}" + def _print_urls(self) -> None: + if self._runner is None: + msg = "Web app is not running" + raise RuntimeError(msg) + + urls = [] + for addr in self._runner.addresses: + # IPv4 (e.g., ('192.168.0.1', 8080)) + if len(addr) == LEN_AF_INET: + urls.append(f"http://{addr[0]}:{addr[1]}") + # IPv6 (e.g., ('::1', 8080, 0, 0)) + elif len(addr) == LEN_AF_INET6: + urls.append(f"http://[{addr[0]}]:{addr[1]}") + else: + msg = f"Unknown address format: {addr}" + raise ValueError(msg) + + log.info("Webserver started: %s", " ".join(urls)) + SDK_WEBSERVER_APP_KEY = web.AppKey("sdk_webserver_app", WebServer) MANIFEST_APP_KEY = web.AppKey("manifest", Manifest)