python-3.xmultithreadingflask-socketio

Send Data Using SocketIO from Oher Module Run by Threading


I have a script, that look like this. And I run the the function using threading.

from flask import Flask
from flask_socketio import SocketIO
import threading
import time

def start_process():
    for i in range(50):
        message = "Hello, world!"
        socketio.emit('message', message)
        print(f"Event triggered! {message}")
        time.sleep(1)

app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="")

if __name__ == "__main__":
    threading.Thread(target=start_process).start()
    socketio.run(app, port=1120, debug=False)

If using the code above, it works. But what if my start_process function is in another file, let's say process_module.py. And the script will be like this.

process_module.py

import time

def start_process():
    for i in range(50):
        message = "Hello, world!"
        # here are command to send the message using socketio
        print(f"Event triggered! {message}")
        time.sleep(1)

and here are the main_script.

from flask import Flask
from flask_socketio import SocketIO
import threading
import time
from process_module import start_process

app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="")

if __name__ == "__main__":
    threading.Thread(target=start_process).start()
    socketio.run(app, port=1120, debug=False)

I want to call the function start_process from the other module and send the message through socket using flask_socektio. I have try some methods, and it's still did not work. How to make it works?


Solution

  • Your question is a bit vague but here is my attempt.

    your main script

    from flask import Flask
    from flask_socketio import SocketIO
    from process_module import start_process
    import threading
    
    app = Flask(__name__)
    socketio = SocketIO(app, cors_allowed_origins="")
    
    if __name__ == "__main__":
        threading.Thread(target=start_process(socketio)).start()
        socketio.run(app, port=1120, debug=False)
    

    and for process_module.py

    import time
    def start_process(socket):
        for i in range(50):
            message = "Hello, world!"
            socket.emit('message', message)
            print(f"Event triggered! {message}")
            time.sleep(1)
    

    The solution was basically passing the socketio as an argument to the start_process function in an external file which we import.