停止 Flask(没有请求上下文)

Jui*_*icy 5 python werkzeug flask python-3.x

从应用程序内停止 Flask 的唯一官方记录的方法只能通过请求上下文来完成:

from flask import request

def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

@app.route('/shutdown', methods=['POST'])
def shutdown():
    shutdown_server()
    return 'Server shutting down...'
Run Code Online (Sandbox Code Playgroud)

这会导致非常丑陋和黑客的场景,如果您希望服务器从进程的另一部分关闭(即:不响应请求并且您没有请求),您几乎必须编写从服务器到自身的请求脚本语境)。这也将终止端点暴露给整个网络(即使它不重要/非产品,如果没有必要,仍然很愚蠢)。

有没有一种干净的方法可以在没有请求上下文的情况下停止 Flask,即:神话app.stop()

为了了解更多背景信息,并且无需深入研究让我在线程中运行 Flask 的深奥原因(我保证对我的程序有意义):

class WebServer:
    def __init__(self):
        self.app = Flask('test')
        self.thread = threading.Thread(target=self.app.run)

        @self.app.route('/')
        def index():
            return 'Hello World'

    def start(self):
        self.thread.start()

    def stop(self):
        # how can I implement this? just getting Flask to end would end the thread!
Run Code Online (Sandbox Code Playgroud)