How to properly terminate a Flask server thread?

64 views Asked by At

I'm trying to make a flask app that can be managed from PyQt5 GUI, but I cannot make the stop server button actually stop the server.

In the pyFlaskyServe.py I made a ServerThread class to start and stop the server:

class ServerThread(threading.Thread):
    def __init__(self, host, port):
        super().__init__()
        self.host = host
        self.port = port
        self.running = False
        self.stop_requested = threading.Event()

    def run(self):
        logging.basicConfig(level=logging.DEBUG)
        self.running = True
        while not self.stop_requested.is_set():
            serve(app, host=self.host, port=self.port)
        self.running = False

    def request_stop(self):
        self.stop_requested.set()

    def is_running(self):
        return self.running

And this is how I'm trying to start and stop from the GUI:

class MainWindow(QMainWindow):
    def check_server_status(self):
        if self.server_thread is not None and self.server_thread.is_running():
            self.start_button.setDisabled(True)
            self.stop_button.setEnabled(True)
        else:
            self.start_button.setEnabled(True)
            self.stop_button.setDisabled(True)
            if self.server_thread is not None and not self.server_thread.is_running():
                self.server_thread.join()
                self.server_thread = None

    def __init__(self):
        super().__init__()

        # Rest of the GUI code

    def start_button_clicked(self):
        serve_port_str = self.port_entry.text()

        # Some validation check before starting

        if self.server_thread is None or not self.server_thread.is_running():
            self.server_thread = ServerThread(self.host, serve_port)
            self.server_thread.start()

    def stop_button_clicked(self):
        self.stop_button.setDisabled(True)
        self.start_button.setEnabled(True)

        if self.server_thread is not None and self.server_thread.is_running():
            self.server_thread.request_stop()
            self.server_thread.join()

def main():
    Qapp = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()

    timer = QTimer(main_window)
    timer.timeout.connect(main_window.check_server_status)
    timer.start(1000)

    main_window.activateWindow()
    main_window.raise_()

    sys.exit(Qapp.exec_())

When I click the stop button the server doesn't stop, rather due to joining thread the GUI freezes. How can I properly stop the server? Also, please don't say anything too complex for a 17-year-old to understand :)

0

There are 0 answers