diff --git a/uvicorn/server.py b/uvicorn/server.py index cca2e850c..6ebfb3252 100644 --- a/uvicorn/server.py +++ b/uvicorn/server.py @@ -83,8 +83,7 @@ async def _serve(self, sockets: list[socket.socket] | None = None) -> None: logger.info(message, process_id, extra={"color_message": color_message}) await self.startup(sockets=sockets) - if self.should_exit: - return + # FIX: make sure always execute the shutdown logic, even if server received a signal during startup await self.main_loop() await self.shutdown(sockets=sockets) @@ -263,8 +262,9 @@ async def shutdown(self, sockets: list[socket.socket] | None = None) -> None: logger.info("Shutting down") # Stop accepting new connections. - for server in self.servers: - server.close() + if hasattr(self, "servers") and self.servers: + for server in self.servers: + server.close() for sock in sockets or []: sock.close() # pragma: full coverage @@ -306,8 +306,9 @@ async def _wait_tasks_to_complete(self) -> None: while self.server_state.tasks and not self.force_exit: await asyncio.sleep(0.1) - for server in self.servers: - await server.wait_closed() + if hasattr(self, "servers") and self.servers: + for server in self.servers: + await server.wait_closed() @contextlib.contextmanager def capture_signals(self) -> Generator[None, None, None]: