项目结构如下:
website/ celery/ task.py socketio/ socket.py views/ index.py init.py manage.py
我的 flask app 在 init 里初始化,celery 在 task 里初始化,socket 在 socket.py 里初始化。 然后在 index 里创建一个路由
@app.route('/index') def indexx(): from website.celery.tasks import test test.delay() return 'a'
test 如下:
from website.socketio.socket import socket @celery.task def test(): # socketio = SocketIO(message_queue='redis://localhost:6379/1') socketio.emit('response',{'data':'sdasda'},broadcast=True) print "aaaa"
然后运行,celery shell 显示任务执行了,但是 socket 发的消息并没有在前端收到怎么办呢?好急 请教各位大神啦!
![]() | 1 ericls 2017-11-29 04:11:06 +08:00 via iPhone 并不是同一个 socket |
![]() | 2 ericls 2017-11-29 04:11:50 +08:00 via iPhone Socket 的后端用的是什么? |
![]() | 3 gogobody OP |
![]() | 4 ericls 2017-11-29 10:03:24 +08:00 via iPhone @gogobody 因为 celery 和 web 是分开的 process 所以你需要有一个共同的后端…… 手机看了一下文档 If using multiple processes, a message queue service is used by the processes to coordinate operations such as broadcasting. The supported queues are Redis, RabbitMQ, and any other message queues supported by the Kombu package. |
![]() | 5 gogobody OP @ericls 我的 socket 是这样初始化的 socketio = SocketIO(app) socketio.run(app),celery 是使用 redis://localhost:6379/0,尝试 socketio = SocketIO(app,message_queue="redis://localhost:6379/0")这样初始化,结果初始化后连接不到 socket 了 |
![]() | 6 ycz0926 2017-11-30 16:16:25 +08:00 ![]() 你可以在 index.py 里起一个 route,这个 route 里执行 emit,test 里直接 request 这个 route 就可以了 |
![]() | 8 ycz0926 2017-12-01 00:18:50 +08:00 @gogobody no thanks,我最近也在弄这个,有另一种实现方式 https://github.com/miguelgrinberg/Flask-SocketIO/issues/47 |