python - flask ,FlaskSocketIO - 运行时错误 : Cannot obtain socket from WSGI environment

标签 python flask websocket 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.

我也在浏览器控制台中收到此错误: 与“ws://localhost:5000/socket.io/?EIO=4&transport=websocket&sid=40NYzDgGYStMR0CEAAAJ”的 WebSocket 连接失败:

我尝试使用 gevent、gevent-websocket 和 eventlet,但这创建了 other issues ,我不确定我是否需要为此用例使用 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

应用.py

from app import create_app, socketio

app = create_app()

if __name__ == '__main__':
    socketio.run(app)

路线.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'

index.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');
            }
        )

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

最佳答案

您正在使用 simple-websocket 包。这个包有一个支持的网络服务器列表。该错误表明您正在使用不在受支持列表中的 Web 服务器。

支持的网络服务器有:

  • Flask 开发服务器(当然,仅用于开发目的)
  • unicorn
  • 小事件
  • 事件

从这个列表来看,生产 Web 服务器的唯一选择似乎是 Gunicorn,因为您说 eventlet/gevent 不能满足您的需求。

Gunicorn 的使用包含在 documentation 中.在该部分中,simple-websocket 是提到的第三个选项。这是示例启动命令:

gunicorn -w 1 --threads 100 module:app

关于python - flask ,FlaskSocketIO - 运行时错误 : Cannot obtain socket from WSGI environment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68019530/

相关文章:

python - 在具有可变参数的函数中使用默认参数。这可能吗?

python - 尝试抓取网页时出现 SSL 错误

python - 运行 Docker 镜像给出 : Unable to load configuration from app. py

java - 我可以使用 HandshakeInterceptor 和 graphql-spring-boot-starter 来获取 Cookie 吗?

node.js - Websocket 后端客户端连接在一段时间后停止接收流更新

python - 根据近似相对距离估计绝对位置

python - Pandas RegEx 提取子字符串上的第一个匹配项,传递的项目数错误

python - 在 Flask 中从后台进程设置缓存

python - 如何在 flask 脚本的@manager.options 中设置默认值

php - 在 C :\wamp\www\bin\chat-server. php 中找不到类 'MyChat\Chat'