Search code examples
pythonflasksocket.io

Flask + SocketIO start/stop subapp with DispatcherMiddleware


I have an Flask server with SocketIO and DispatcherMiddleware now i want to start/stop an subapp on runtime if i call the routes (start/stop) with the subapp name as an url argument than the app should start/stop but not the whole server only the subapp.

Here are my setup (init app).

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)

Here are the subapps.

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)

Thanks for any help or idea how i can make this.


Solution

  • I have found an solution.

    Here are the codes.

    stop

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

    start

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