【问题标题】:Flask-SocketIO emit not working from different module?Flask-SocketIO 发射不能从不同的模块工作?
【发布时间】:2018-08-06 19:23:41
【问题描述】:

当我从 server.py 文件中调用 socket.emit('someevent','blahblah') 时,一切都按预期工作。但是当我尝试从 bot.py 调用相同的方法时,什么也没有发生。

代码:

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

我知道我使用的是标准线程机制,但它似乎与线程无关,因为我可以在 Bot 类中创建一个随机静态方法,在从主文件创建单独的线程之前调用它,什么都不会发生。 thread_manager 模块不包含任何会干扰的内容,但我什至将它从图片中完全删除,并且没有任何改变。有什么线索吗?

【问题讨论】:

    标签: python-3.x flask-socketio


    【解决方案1】:

    原来这完全与循环导入有关。从入口点拆分应用程序声明是可行的,这样我就有了第三个参考文件,可以从中导入 socketio。

    【讨论】:

    • 您刚刚解决了 2 天的故障排除问题,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    相关资源
    最近更新 更多