Flask、FlaskSocketIO - RuntimeError:无法从 WSGI 环境获取套接字

Dr.*_*ein 9 python websocket flask flask-socketio

当我尝试在应用程序中使用使用 websockets 的功能时,我在控制台中收到此错误:

File "/Users/user/venv/lib/python3.7/site-packages/simple_websocket/ws.py", line 138, in __init__
    raise RuntimeError('Cannot obtain socket from WSGI environment.')
RuntimeError: Cannot obtain socket from WSGI environment.
Run Code Online (Sandbox Code Playgroud)

我还在浏览器控制台中收到此错误: WebSocket connection to 'ws://localhost:5000/socket.io/?EIO=4&transport=websocket&sid=40NYzDgGYStMR0CEAAAJ' failed:

我尝试使用 gevent、gevent-websocket 和 eventlet,但这会产生其他问题,并且我不确定是否需要在该用例中使用 gevent 或 eventlet。

这是其余的相关代码:

__初始化__.py

from flask_socketio import SocketIO
...

socketio = SocketIO()

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(Config)

    socketio.init_app(app, cors_allowed_origins='*')

    ...

    return app
Run Code Online (Sandbox Code Playgroud)

应用程序.py

from app import create_app, socketio

app = create_app()

if __name__ == '__main__':
    socketio.run(app)
Run Code Online (Sandbox Code Playgroud)

routes.py 这只接受 POST 请求,因为我从 Celery 任务将数据发送到此路由

from app import socketio

...

@main_bp.route('/send_message', methods=['POST'])
def send_message():
    
    ...

    socketio.emit('test_message', {'msg':'Test'}, namespace='/test')

    return 'Results Sent'
Run Code Online (Sandbox Code Playgroud)

索引.html

        var socket = io.connect('http://localhost:5000/test');
        socket.on('connect', function(){
            console.log('Connected to socket')

        });

        socket.on('test_message', function(message){
            console.log('Received test message');
            }
        )
Run Code Online (Sandbox Code Playgroud)

请注意,在浏览器控制台中,我将看到“已连接到套接字”,但看不到“已收到测试消息”

小智 0

也许您可以打开记录器和engine.io记录器。这可以让您了解问题所在。

不要同时使用 eventlet 和 gevent。使用任何一个并卸载另一个。