Search code examples
flaskflask-socketio

SocketIO with Flask for specific page of a website


I'm having a flask website with different apps in different routes:

@app.route('/')
def index():
    ......

@app.route('app1')
def app1():
    ......
    return render_template('app1.html')

@app.route('app2')
def app1():
    ......
    return render_template('app2.html')

......

app = Flask(__name__)

if __name__ == "__main__":
    app.run()

My question is how I can have another app3, if user go to that page, then use SocketIO (because that web page will handle real-time bidirectional communication) but without change existing structures (the other pages do NOT use socket).

I see the doc is using:

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

if __name__ == '__main__':
    socketio.run(app)

Which run all of app with the socket.


Solution

  • What you did is the correct thing. The Socket.IO server will be activated only when a client connects to it. If your app1 and app2 pages do not initiate connections, then the Socket.IO server will pass-through those connections to Flask and only engage with the clients that are on the app3 page, assuming you add a Socket.IO client to that page.