Flask + SocketIO start/stop 带有 DispatcherMiddleware 的子应用程序

Flask + SocketIO start/stop subapp with DispatcherMiddleware

我有一个带有 SocketIO 和 DispatcherMiddleware 的 Flask 服务器,现在我想在运行时 start/stop 一个子应用程序,如果我使用子应用程序名称作为 url 调用路由 (start/stop)参数比应用程序应该 start/stop 但不是整个服务器只有子应用程序。

这是我的设置(初始化应用程序)。

init.py

from flask import Flask
from flask_socketio import SocketIO
from werkzeug.middleware.dispatcher import DispatcherMiddleware

from app1 import app1
from app2 import app2


# Setup the main app.
app = Flask(__name__)


# Stop the Blueprint app.
@app.route('/stop<app>', methods=['GET'])
def stop_app(app):
    pass


# Start the Blueprint app.
@app.route('/start<app>', methods=['GET'])
def start_app(app):
    pass


# Create the dispatcher with all Blueprint apps.
app.wsgi_app = DispatcherMiddleware(app, {"/app1": app1, "/app2": app2})


# Create the socketio app.
socketio = SocketIO(app, async_mode="threading")


# Start the app.
socketio.run(app, "localhost", 80)

这是子应用程序。

app1.py

from flask import Flask


# Setup the Blueprint app.
app1 = Flask(__name__)


# INFO Create Main Blueprints.
hello = Blueprint('hello', __name__)
@hello.route('/hello', methods=['GET'])
def hello_blp():
    print("hello")


# Register all Blueprints.
app1.register_blueprint(hello)

app2.py

from flask import Flask


# Setup the Blueprint app.
app2 = Flask(__name__)


# INFO Create Main Blueprints.
world = Blueprint('world', __name__)
@world.route('/world', methods=['GET'])
def world_blp():
    print("world")


# Register all Blueprints.
app2.register_blueprint(world)

感谢您提供任何帮助或建议我如何做到这一点。

我找到了解决办法。

这是代码。

停止

# Stop the Blueprint app.
@app.route('/stop<app_name>', methods=['GET'])
def stop_app(app_name):
    del app.wsgi_app.wsgi_app.mounts[f"/{app_name}"]

开始

# Start the Blueprint app.
@app.route('/start<app_name>', methods=['GET'])
def start_app(app_name):
    app.wsgi_app.wsgi_app.mounts.update({f"/{app_name}": create_app(app_name)})