Milan Velebit
Milan Velebit

Reputation: 2027

Flask-SocketIO emit not working from different module?

When I invoke socket.emit('someevent','blahblah') from server.py file, everything works as intended. But when I try to invoke the same method from bot.py, nothing happens.

Code:

server.py:

import eventlet
eventlet.monkey_patch()
import eventlet.wsgi
from flask import Flask, render_template, jsonify, request, abort
from flask_cors import CORS, cross_origin
import threading
from thread_manager import ThreadManager
from flask_socketio import SocketIO, emit, send

cho = Flask(__name__, static_folder="client/dist", template_folder="client/dist")
socketio = SocketIO(cho)
cors = CORS(cho)

threadmanager = ThreadManager()     # Start the thread manager

import bot as bot_module

@cho.route('/api/start_bot', methods=['POST'])
@cross_origin()
def startBot():
    """
    Begins the execution
    :return:
    """
    if request.method == 'POST':
        request_json = request.get_json()
        .... more code 
        bot = bot_module.Bot(some_args_from_request_above)
        bot_thread = threading.Thread(target=bot.run)
        bot_thread.start()
        if threadmanager.check_thread_status(bot_name):
            print('Thread is alive!')
            return ok_res
        else:
            print('Thread seems inactive')
            return bad_res

if __name__ == "__main__":
    eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 5000)), cho, debug=True)

bot.py

import server
class Bot: 
 .....
    def run(self):
        server.socketio.emit('someevent', 'w0w') # <-- nothing happens

I know I'm using the standard threading mechanism but it seems to not be related to threads whatsoever as I can create a random static method inside the Bot class, invoke it before creating a separate thread from the main file and nothing will happen. The thread_manager module contains nothing that would interfere, but I've even removed it completely from the picture and nothing changed. Any clues?

Upvotes: 0

Views: 1132

Answers (1)

Milan Velebit
Milan Velebit

Reputation: 2027

Turns out this was completely related to the circular import. Splitting the app declaration from the entrypoint worked, so that I'd have a third reference file which to import socketio from.

Upvotes: 1

Related Questions