首页 > 解决方案 > 如何在事件处理程序之外发出 socketio 消息

问题描述

我正在尝试从 celery 任务中发出消息。但是,即使尝试广播,发出消息也不会到达客户端:

@celery.task(bind=True)
def search_pdf(self, path, keyword, room):#, url):
    socketio.emit('message', {'msg': 'results' + ':' + 'message from a celery'}, namespace='/chat', broadcast=True)
    socketio.emit('message', {'msg': 'results' + ':' + 'message from a celery'}, broadcast=True)

在调试时,似乎每当我在 socketio 事件处理程序之外调用它时,emit 都不会到达客户端,所以一定有一些我误解的东西flask-socketio,有人可以启发我吗?

作为参考,这是我在create_app()函数中的初始化调用:

socketio.init_app(app, async_mode='eventlet', message_queue=app.config['CELERY_BROKER_URL'])

这是我的芹菜应用程序功能:

def create_celery_app(app=None):
    """
    Create a new Celery object and tie together the Celery config to the app's
    config. Wrap all tasks in the context of the application.

    :param app: Flask app
    :return: Celery app
    """
    app = app or create_app()
    # app.app_context().push()

    celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'],
                    include=CELERY_TASK_LIST)
    celery.conf.update(app.config)
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask
    return celery

标签: flasksocket.ioceleryflask-socketio

解决方案


推荐阅读