Как отключить многопоточность и FASTAPI с помощью Ctrl+C?Python

Программы на Python
Anonymous
Как отключить многопоточность и FASTAPI с помощью Ctrl+C?

Сообщение Anonymous »

Я хотел бы остановить выполнение процесса и FASTAPI с помощью Ctrl+C в Python. Но я получаю ошибки исключения KeyboardInterrupt, как правильно остановить потоки и FAST API

Код: Выделить всё

from fastapi import FastAPI
import threading
import time
import signal
from datetime import datetime, timedelta

from model import core
from model.database import engine, SessionLocal, get_db
from model.core import Timestamp
from routers.timestamps import router as timestamps_router

core.Base.metadata.create_all(bind=engine)

app = FastAPI()

app.include_router(router=timestamps_router)

def record_timestamp():
while True:
db = SessionLocal()
new_timestamp = Timestamp(timestamp=datetime.utcnow())
db.add(new_timestamp)
db.commit()
db.close()
time.sleep(5)

def delete_old_timestamps():
while True:
db = SessionLocal()
one_minute_ago = datetime.utcnow() - timedelta(minutes=1)
db.query(Timestamp).filter(Timestamp.timestamp < one_minute_ago).delete()
db.commit()
db.close()
time.sleep(10)

@app.on_event("startup")
def startup_event():
get_db()
t1 = threading.Thread(target=record_timestamp)
t2 = threading.Thread(target=delete_old_timestamps)

t1.start()
t2.start()

Я пытался подключить сигнал с помощью ChatGPT, но тоже не получилось

Подробнее здесь: https://stackoverflow.com/questions/785 ... with-ctrlc

Вернуться в «Python»