如何使用Flask-SocketIO修复此KeyError错误?

时间:2016-06-28 02:53:16

标签: python-2.7 flask socket.io flask-socketio

当我搜索时,这似乎是一个常见的问题,但我似乎无法找到可行的解决方案。据我所知,错误并不是很有用,因为它并没有真正告诉你为什么保存的会话消失了。

 Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/eventlet/wsgi.py", line 481, in handle_one_response
    result = self.application(self.environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask_socketio/__init__.py", line 37, in __call__
    start_response)
  File "/usr/local/lib/python2.7/dist-packages/engineio/middleware.py", line 47, in __call__
    return self.engineio_app.handle_request(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/socketio/server.py", line 303, in handle_request
    return self.eio.handle_request(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/engineio/server.py", line 226, in handle_request
    environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/engineio/socket.py", line 79, in handle_get_request
    start_response)
  File "/usr/local/lib/python2.7/dist-packages/engineio/socket.py", line 118, in _upgrade_websocket
    return ws(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/engineio/async_eventlet.py", line 13, in __call__
    return super(WebSocketWSGI, self).__call__(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/eventlet/websocket.py", line 127, in __call__
    self.handler(ws)
  File "/usr/local/lib/python2.7/dist-packages/engineio/socket.py", line 180, in _websocket_handler
    self.receive(pkt)
  File "/usr/local/lib/python2.7/dist-packages/engineio/socket.py", line 48, in receive
    self.server._trigger_event('message', self.sid, pkt.data)
  File "/usr/local/lib/python2.7/dist-packages/engineio/server.py", line 330, in _trigger_event
    return self.handlers[event](*args)
  File "/usr/local/lib/python2.7/dist-packages/socketio/server.py", line 429, in _handle_eio_message
    self._handle_event(sid, pkt.namespace, pkt.id, pkt.data)
  File "/usr/local/lib/python2.7/dist-packages/socketio/server.py", line 371, in _handle_event
    r = self._trigger_event(data[0], namespace, sid, *data[1:])
  File "/usr/local/lib/python2.7/dist-packages/socketio/server.py", line 397, in _trigger_event
    return self.handlers[namespace][event](*args)
  File "/usr/local/lib/python2.7/dist-packages/flask_socketio/__init__.py", line 199, in _handler
    self.server.environ[sid]['saved_session'] = {}
KeyError: 'baee47721e474a1a9885b41ee0ce1847'

1 个答案:

答案 0 :(得分:3)

首先,升级以下软件包:flask-socketio,python-socketio和python-engineio。

我认为这将解决您的问题。旧版本的Flask-SocketIO出现此问题。我为这种情况确定的原因是处理程序函数(这些用socketio.on()装饰器装饰的函数)运行了很长时间而没有正确释放CPU。如果函数运行时间超过60秒而未释放CPU,则系统错误地认为客户端已经消失并断开会话,导致稍后访问该会话时出现KeyError。

最新版本中解决了该错误。但另外请确保释放CPU,以便在后台运行的其他任务有机会完成他们需要做的事情。