I would like to call my celery task when a websocket client connects to the socket server. When I try calling it from the connect event it causes the application to time out and the client does not receive the emit.
Below is an example of the code for the application:
from flask import Flask
from flask_socketio import SocketIO
import eventlet
from celery import Celery
import time
eventlet.monkey_patch(socket=True)
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
socketio = SocketIO(app, async_mode='eventlet', logger=True, engineio_logger=True, message_queue='redis://127.0.0.1:6379' )
celery = Celery(app.name, broker='redis://127.0.0.1:6379')
celery.conf.update(app.config)
@app.route('/')
def home():
return 'Hello World!'
@socketio.on('connect')
def connect():
print('Client connected, calling celery task...')
celeryTask(1,2)
@celery.task()
def celeryTask(x,y):
print('Celery task called!')
local_socketio = SocketIO(app, logger=True, engineio_logger=True, message_queue='redis://127.0.0.1:6379')
while True:
local_socketio.emit('add', {'data': x+y})
time.sleep(60)
if __name__ == '__main__':
socketio.run(app, debug=True)
Any help would be greatly appreciated!
2
Answers
Maybe try to put @celery.task() before @socketio.on(‘connect’). That might help.
The
socketio
instance that you are using in your Celery task should not be initialized with theapp
instance from Flask. This isn’t a web server, is just an auxiliary emitter.If that does not work, you will need to add logs to your question, as that provide more clues.