Impossible to stop a too long job or startup event #10135
-
First Check
Commit to Help
Example Codeimport logging
import time
from fastapi import FastAPI
app = FastAPI()
@app.on_event("startup")
def startup_event():
logger = logging.getLogger("uvicorn")
logger.info("Starting up...")
while True:
logger.info("long process running...")
time.sleep(1)
@app.get("/")
async def home():
while True:
logger.info("other long process running...")
time.sleep(1)
return {"success": "Welcome to the API!"}DescriptionI happen to have a long startup event waiting for other microservices to set up. I noticed that it was not possible to stop the process with a usual ^C or using signals. It is really not handy when it comes to testing (manual and auto). I looked into the lifespan part of the doc but couldn't find something similar. To reproduce, simply run the code with I may be missing something big, but this feels weird. Operating SystemLinux Operating System DetailsNo response FastAPI Version0.101.1 Pydantic Version2.2.1 Python Version3.9.16 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
|
Looking at the logs I see that this msg appears after @app.on_event("startup"), so I suppose CTRL+C is only available after "startup". INFO: Application startup complete A possible workaround that I just tested is using "--reload" flag, which should work. |
Beta Was this translation helpful? Give feedback.
-
|
As JavierSanchezCastro mentioned, it comes from Uvicorn (Kludex/uvicorn#1301). The solution from here is to set the handler for import asyncio
from contextlib import asynccontextmanager
import logging
import signal
import sys
from fastapi import FastAPI
logger = logging.getLogger("uvicorn")
def receive_signal(signalNumber, frame):
print("Received:", signalNumber)
sys.exit()
@asynccontextmanager
async def lifespan(app: FastAPI):
signal.signal(signal.SIGINT, receive_signal)
logger.info("Starting up...")
for i in range(10):
logger.info(f"long process running ({i})...")
await asyncio.sleep(1)
yield
logger.info("Shutdown...")
app = FastAPI(lifespan=lifespan) |
Beta Was this translation helpful? Give feedback.
As JavierSanchezCastro mentioned, it comes from Uvicorn (Kludex/uvicorn#1301).
The solution from here is to set the handler for
SIGINTsignal: