9

我正在使用Flask构建一个网站,其中我还使用Flask-socketIO使用 Websockets ,但有一件事我不明白。

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

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

但是假设我想在保存文件时向用户发出消息。这意味着我需要从发布文件的视图中发出一条消息。所以根据flask_socketio docs我可以在发射中添加一个命名空间。所以我写了这个:

@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'
4

1 回答 1

26

引用 Miguel Grinberg在 Flask-SocketIO GitHub 上的一个开放问题页面上的回复:

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

举个例子:

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)})
于 2015-05-08T14:11:50.423 回答