Gracefully shutdown uvicorn.Server on task cancellation in run()

This commit is contained in:
A i 2025-05-28 21:50:42 +08:00
parent 27af7a6f22
commit 101c513aeb

View File

@ -2,6 +2,7 @@ import json
import os import os
import logging import logging
import socket import socket
import asyncio
from contextlib import AsyncExitStack, asynccontextmanager from contextlib import AsyncExitStack, asynccontextmanager
from typing import Optional from typing import Optional
@ -341,4 +342,9 @@ async def run(
) )
server = uvicorn.Server(config) server = uvicorn.Server(config)
await server.serve() try:
await server.serve()
except asyncio.CancelledError:
server.should_exit = True
await server.shutdown()
raise