pythonsocketsflaskflask-socketio

How to execute some code before flask socket.io server starts?


I have an application based on flask-socketIO. I want to execute some code just before flask server starts. My app.py file looks like this:

from flask import Flask
from flask_cors import CORS
from flask_socketio import SocketIO


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

@socketio.on('connect')
def test_connect():
    print("Client connected")


@socketio.on('disconnect')
def test_disconnect():
    print('Client disconnected')

if __name__ == "__main__":
    socketio.run(app, debug=False, host='0.0.0.0')

When I run the program: FLASK_APP=app.py flask run --host=0.0.0.0, I get console output as follows: * Serving Flask-SocketIO app "app" Then some clients connect to my app and it works as I expected, but I want to see print which is above socketio.run(app).

How can I execute code before the start of the server?


Solution

  • Use before_fist_request

    @app.before_first_request
    def your_function():
        print("execute before server starts")
    

    Update: enter image description here