停止线程内的 dash 服务器不起作用

问题描述 投票:0回答:1

我试图停止线程内的破折号服务器,但它不起作用:

这是这个问题的一个小例子:

import threading
import requests
from dash import Dash, html
from flask import Flask, request
import logging
import time

# Setup Logger
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(threadName)s, %(levelname)s] %(message)s",
    handlers=[
        logging.StreamHandler()
    ]
)

# Create Flask server and associate it with the Dash app
flask_app = Flask(__name__)
app = Dash(__name__, server=flask_app)

# Define a simple layout
app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),
    html.P(children='This is a simple Dash app for testing.'),
    html.Button('Click Me', id='button')
])

# Define a shutdown route
@app.server.route('/shutdown', methods=['POST'])
def shutdown():
    shutdown_server = request.environ.get('werkzeug.server.shutdown')
    if shutdown_server is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    shutdown_server()
    return 'Server shutting down...'

# Function to run the server
def run_server():
    logging.info("Starting Dash server")
    app.run_server(debug=True, use_reloader=False)

# Function to stop the server
def stop_server():
    logging.info("Sending shutdown request")
    try:
        requests.post('http://127.0.0.1:8050/shutdown')
    except requests.RequestException as e:
        logging.error(f"Error sending shutdown request: {e}")
    logging.info("Joining server thread")
    server_thread.join()

# Start the server in a new thread
server_thread = threading.Thread(target=run_server)
server_thread.start()

# Start the server, wait a few seconds, then stop it
time.sleep(5)
stop_server()
logging.info("Server stopped")

当我运行此脚本时,程序挂在 server_thread.join() 处并且不会退出。使用kill pid 对我来说不实用,因为我在GUI 应用程序中运行我的程序。杀死 pid 也会破坏 GUI。

python plotly-dash python-multithreading
1个回答
0
投票

向服务器线程发送停止信号怎么样?例如这样的:

from signal import pthread_kill, SIGINT

# Function to stop the server
def stop_server(thread_id: int):
    logging.info("Sending shutdown request")
    pthread_kill(thread_id, SIGINT)
    
# Start the server in a new thread
server_thread = threading.Thread(target=run_server, 
                                 name='dash_server', 
                                 daemon=True)

server_thread.start()

# Start the server, wait a few seconds, then stop it
time.sleep(10)
stop_server(server_thread.ident)
logging.info("Server stopped")
© www.soinside.com 2019 - 2024. All rights reserved.