如何使用Flask-Sockets?得到一个KeyError:'wsgi.websocket'

kra*_*r65 7 python sockets websocket flask flask-sockets

我正在尝试使用Flask-Sockets和示例代码:

sockets = Sockets(app)

@sockets.route('/echo')
def echo_socket(ws):
    while True:
        message = ws.receive()
        ws.send(message)
Run Code Online (Sandbox Code Playgroud)

不幸的是,当我使用我的浏览器转到url/echo时,它给出了一个错误说:

File "/Library/Python/2.7/site-packages/Flask-0.10-py2.7.egg/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask_sockets.py", line 37, in __call__
environment = environ['wsgi.websocket']
KeyError: 'wsgi.websocket'
Run Code Online (Sandbox Code Playgroud)

有人在想我做错了吗?欢迎所有提示!

[编辑] @jbub - 感谢您的提示!所以首先我现在使用gunicorn而不是内置的开发服务器.所以我开始使用它gunicorn -k flask_sockets.worker -b 0.0.0.0:5000 main:app.然后我将下面的代码插入到views.py中,其中echo_test.html是您提供的代码.当我现在访问/ echo_test时,我确实得到一个提示"套接字关闭".

sockets = Sockets(app)

@sockets.route('/echo')
def echo_socket(ws):
    while True:
        message = ws.receive()
        ws.send(message)

@app.route('/echo_test', methods=['GET'])
def echo_test():
    return render_template('echo_test.html')
Run Code Online (Sandbox Code Playgroud)

但是,假设我的目标是在页面上有一个单词(从列表中随机选择),该单词将从列表中随机选择的其他值进行更新.你有任何关于实现这一目标的提示吗?

jbu*_*bub 8

啊,这就是问题,你不能只是通过常规的GET请求访问websocket端点,这样wsgi.websocket就不会设置为environ.

也使用gunicorn而不是开发服务器,它配备预配置的工作人员:

# install from pip
pip install gunicorn

# run app located in test.py module (in test.py directory)
gunicorn -k flask_sockets.worker test:app
Run Code Online (Sandbox Code Playgroud)

我在这里做了快速示例,请务必更新地址和端口以匹配您的设置.

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript">
       var ws = new WebSocket("ws://localhost:8000/echo");
       ws.onopen = function() {
           ws.send("socket open");
       };
       ws.onclose = function(evt) {
           alert("socket closed");
       };
    </script>
  </head>
</html>
Run Code Online (Sandbox Code Playgroud)

这样浏览器就会向服务器发送请求,表明它希望将协议从HTTP切换到WebSocket.

请在此处阅读更多有关websockets的内容: