[Python] Flask-Socketio not emitting in worker thread

Discussão em 'Python' iniciado por Stack, Fevereiro 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have a program with a queue and a worker thread that executes everything in the queue. When the thread is done processing a job, it should emit some data. It says it is emitting, but the client side doesn't receive the message. When I emit something using the exact same command in the test endpoint, it does work.

    from flask import Flask, render_template, request, session
    from flask_socketio import SocketIO, emit
    from threading import Thread
    from queue import Queue
    import time

    app = Flask(__name__)
    socketio = SocketIO(app, engineio_logger=True, logger=True, cors_allowed_origins="*")
    job_queue = Queue()

    def worker():
    while True:
    sid, job = job_queue.get()
    if job is None:
    break

    print(f"Processing {job}", flush=True)
    time.sleep(2)


    socketio.emit("response", {"filename": job}, to=sid)
    print(f"Emitted response to {sid}", flush=True)

    @app.route('/')
    def index():
    return render_template('test.html')

    @app.route("/test", methods=["POST"])
    def test():
    sid = request.args.get('sid')
    job_queue.put((sid, "test"))
    socketio.emit("response", {"filename": "test"}, to=sid)
    return "OK", 200

    @socketio.on('connect', namespace='/')
    def connected():
    print("Connected", flush=True)

    if __name__ == '__main__':
    Thread(target=worker, daemon=True).start()
    socketio.run(app, debug=True)


    I have added the sid as a parameter to the emit because clients are given a room with their sid name. Like this, I can get past the socketio emitting out of scope error.

    I have also tried to use socketio.start_background_task(), but this didn't work either.

    Continue reading...

Compartilhe esta Página