我有一个带有SocketIO和DispatcherMiddleware的Flask服务器,现在我想在运行时启动/停止一个子应用程序,如果我用子应用程序名称作为url参数调用路由(启动/停止(,那么应用程序应该启动/停止,而不是整个服务器——只有子应用程序。
这是我的设置(init应用程序(。
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)})