launch.py 851 B

12345678910111213141516171819202122232425262728293031323334
  1. import asyncio
  2. import signal
  3. from typing import Any
  4. import uvicorn
  5. from fastapi import FastAPI
  6. from loguru import logger
  7. async def serve_http(app: FastAPI, **uvicorn_kwargs: Any):
  8. config = uvicorn.Config(app, **uvicorn_kwargs)
  9. server = uvicorn.Server(config)
  10. loop = asyncio.get_running_loop()
  11. server_task = loop.create_task(server.serve())
  12. def signal_handler() -> None:
  13. # prevents the uvicorn signal handler to exit early
  14. server_task.cancel()
  15. async def dummy_shutdown() -> None:
  16. pass
  17. loop.add_signal_handler(signal.SIGINT, signal_handler)
  18. loop.add_signal_handler(signal.SIGTERM, signal_handler)
  19. try:
  20. await server_task
  21. return dummy_shutdown()
  22. except asyncio.CancelledError:
  23. logger.info("Gracefully stopping http server")
  24. return server.shutdown()