Flask-SocketIO - 如何从子进程发出事件

问题描述 投票:0回答:1

我有一个Flask应用程序,在某些休息时,使用ProcessPoolExecutor运行多个模块。

更新:将redis添加为消息队列(使用docker,redis作为redis的主机)

socketio = SocketIO(app, message_queue='redis://redis')

(...)

def emit_event(evt, message):
    socketio.emit(evt, message, namespace='/test')

@app.route('/info', methods=['GET'])
def info():
    emit_event('update_reports', '')

(...)
if __name__ == "__main__":
    socketio.run(host='0.0.0.0', threaded=True)

现在我添加了redis,它在从主应用程序发出时仍然有效。这里有一些来自我正在运行子流程的代码:

def __init__(self):
    self.executor = futures.ProcessPoolExecutor(max_workers=4)
    self.socketio = SocketIO(async_mode='eventlet', message_queue='redis://redis')

    (...)
    future = self.executor.submit(process, params)
    future.add_done_callback(functools.partial(self.finished_callback, pid))

然后在那个回调我调用emit_event方法:

def finished_callback(self, pid, future):
    pid.status = Status.DONE.value
    pid.finished_at = datetime.datetime.utcnow
    pid.save()

    self.socketio.emit('update_reports', 'done', namespace='/test')

从我的控制器获取和向客户端发送/发送消息的工作正常,如果我从curl或postman调用/ info我的客户端获取消息 - 但是 - 当尝试从此子进程回调中以相同的方式发出事件时,现在它显示了这个错误:

这主要用于通知,例如通知长时间进程已完成以及类似的事情。

INFO:socketio:emitting event "update_reports" to all [/test] ERROR:socketio:Cannot publish to redis... retrying ERROR:socketio:Cannot publish to redis... giving up

我做错了什么?

谢谢!

python-3.x flask socket.io flask-socketio
1个回答
1
投票

在设置Flask-SocketIO扩展时需要遵循特定的规则,以便外部进程可以发出,包括使用主要和外部进程用来协调工作的消息队列。有关说明,请参阅文档的Emitting from an External Process部分。

© www.soinside.com 2019 - 2024. All rights reserved.