diff --git a/tests/test_cli.py b/tests/test_cli.py index 8c54e6d19..129197707 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -119,7 +119,10 @@ def test_cli_uds(uds_file: Path) -> None: # pragma: py-win32 result = runner.invoke(cli, ["tests.test_cli:App", "--workers=2", "--uds", str(uds_file)]) assert result.exit_code == 0 - assert result.output == "" + assert ( + result.output + == "WARNING: ASGI app factory detected. Using it, but please consider setting the --factory flag explicitly.\n" + ) mock_bind_socket.assert_called_once() mock_run.assert_called_once() assert not uds_file.exists() diff --git a/uvicorn/config.py b/uvicorn/config.py index 65dfe651e..1bacdd9be 100644 --- a/uvicorn/config.py +++ b/uvicorn/config.py @@ -392,9 +392,31 @@ def configure_logging(self) -> None: logging.getLogger("uvicorn.access").handlers = [] logging.getLogger("uvicorn.access").propagate = False + def check_load_app(self) -> Any: + try: + app = import_from_string(self.app) + except ImportFromStringError as exc: + logger.error("Error loading ASGI app. %s" % exc) + sys.exit(1) + + try: + app = app() + except TypeError as exc: + if self.factory: + logger.error("Error loading ASGI app factory: %s", exc) + sys.exit(1) + else: + if not self.factory: + logger.warning( + "ASGI app factory detected. Using it, " "but please consider setting the --factory flag explicitly." + ) + return app + def load(self) -> None: assert not self.loaded + self.loaded_app = self.check_load_app() + if self.is_ssl: assert self.ssl_certfile self.ssl: ssl.SSLContext | None = create_ssl_context( @@ -430,24 +452,6 @@ def load(self) -> None: self.lifespan_class = import_from_string(LIFESPAN[self.lifespan]) - try: - self.loaded_app = import_from_string(self.app) - except ImportFromStringError as exc: - logger.error("Error loading ASGI app. %s" % exc) - sys.exit(1) - - try: - self.loaded_app = self.loaded_app() - except TypeError as exc: - if self.factory: - logger.error("Error loading ASGI app factory: %s", exc) - sys.exit(1) - else: - if not self.factory: - logger.warning( - "ASGI app factory detected. Using it, " "but please consider setting the --factory flag explicitly." - ) - if self.interface == "auto": if inspect.isclass(self.loaded_app): use_asgi_3 = hasattr(self.loaded_app, "__await__") diff --git a/uvicorn/main.py b/uvicorn/main.py index 96a10d538..11b050284 100644 --- a/uvicorn/main.py +++ b/uvicorn/main.py @@ -561,6 +561,7 @@ def run( factory=factory, h11_max_incomplete_event_size=h11_max_incomplete_event_size, ) + config.check_load_app() server = Server(config=config) if (config.reload or config.workers > 1) and not isinstance(app, str): @@ -577,8 +578,8 @@ def run( Multiprocess(config, target=server.run, sockets=[sock]).run() else: server.run() - except KeyboardInterrupt: - pass # pragma: full coverage + except KeyboardInterrupt: # pragma: full coverage + pass finally: if config.uds and os.path.exists(config.uds): os.remove(config.uds) # pragma: py-win32