如何从websocket端点外部发出websocket消息?

时间:2015-05-08 13:09:13

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

我使用Flask构建网站,我也使用Flask-socketIO使用网页插件,但有一点我不明白。

我构建了一个聊天功能。当一个用户发送消息时,我使用websockets将该消息发送到服务器,之后我从同一个呼叫中向另一个用户发送消息:

@socketio.on('newPM', namespace='/test')
@login_required_with_global
def io_newMessage(theJson):
    emit('message', {'message': theJson['message']}, room=str(theJson['toUserId']))

但是,让我们说我想在保存文件时向用户发出消息。这意味着我需要从文件POST的视图中发出消息。所以根据flask_socketio docs我可以在emit中添加一个名称空间。所以我写了这个:

@app.route('/doc', methods=['POST'])
@login_required
def postDoc():
    saveDocument(request.files['file'], g.user.id)
    emit('my response', {'data': 'A NEW FILE WAS POSTED'}, room=current_user.id, namespace='/test')
    return jsonify({'id': str(doc.id)})

但是看到下面的堆栈跟踪仍然存在命名空间的问题; werkzeug有一个AttributeError: 'Request' object has no attribute 'namespace'

有人知道我在这里做错了什么吗?或者这是flask_socketio中的错误?欢迎所有提示!

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/local/lib/python2.7/dist-packages/flask_login.py", line 758, in decorated_view
    return func(*args, **kwargs)
  File "/home/vg/app/views.py", line 768, in emitNotificationCount
    emit('menuInit', emitJson, room=current_user.id, namespace='/test')
  File "/usr/local/lib/python2.7/dist-packages/flask_socketio/__init__.py", line 444, in emit
    return request.namespace.emit(event, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 338, in __getattr__
    return getattr(self._get_current_object(), name)
AttributeError: 'Request' object has no attribute 'namespace'

1 个答案:

答案 0 :(得分:11)

引自Miguel Grinberg对an open issue page on the Flask-SocketIO GitHub的回应:

  

当您想要从常规路线发射时,您必须使用   socketio.emit(),只有套接字处理程序具有socketio上下文   调用普通的emit()。

以此为例:

from flask_socketio import SocketIO

app = Flask(__name__)
app.config.from_object('config')
socketio = SocketIO(app)

@app.route('/doc', methods=['POST'])
def postDoc():
    saveDocument(request.files['file'], g.user.id)
    socketio.emit('my response', {'data': 'A NEW FILE WAS POSTED'}, room=current_user.id)
    return jsonify({'id': str(doc.id)})