在我正在使用Flask构建的网站中,人们可以互相发送 PM。当用户收到 pm 时,我现在想实现一个类似于 StackOverflow 的通知。由于 SO 使用 websockets 实现了这一点,因此我使用本教程开始使用 websockets关于实现Flask-socketIO(与Socket.io一起使用)。
我下载了教程制作的示例,并且我了解其中的代码。然而,我不明白的是:
- 我如何知道登录的人是否打开了网站并连接到 websockets?
- 如何向该特定用户发送消息?
因此,假设我有一个简单的路线,人们可以在其中向另一个用户发布 PM:
@app.route('/admin/pm', methods=['GET', 'POST'])
@login_required
def pms():
if request.method == 'POST':
savePM(g.user.id, request.form['toUserId'], request.form['text'])
# How do I emit a message here to the user to whom this message is sent?
return render_template('sendPM.html')
我的评论已经说过:我如何向从那里发送此消息的用户发出消息?欢迎所有提示!
[编辑] 按照 Miguel 的提示,我想创建一个名称为 的房间user.id
,所以我现在创建了以下连接和断开连接事件:
@socketio.on('connect', namespace='/test')
@login_required
def websocketConnect():
join_room(g.user.id)
emit('my response', {'data': 'Connected'}, room=g.user.id)
@socketio.on('disconnect', namespace='/test')
@login_required
def websocketDisconnect():
leave_room(g.user.id)
print('Client disconnected')
但是在连接后,我得到了下面的堆栈跟踪。对象不是g
用socketio路由创建的吗?
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/gevent/greenlet.py", line 327, in run
result = self._run(*self.args, **self.kwargs)
File "/Library/Python/2.7/site-packages/socketio/virtsocket.py", line 403, in _receiver_loop
retval = pkt_ns.process_packet(pkt)
File "/Library/Python/2.7/site-packages/socketio/namespace.py", line 164, in process_packet
return self.call_method_with_acl('recv_connect', packet)
File "/Library/Python/2.7/site-packages/socketio/namespace.py", line 240, in call_method_with_acl
return self.call_method(method_name, packet, *args)
File "/Library/Python/2.7/site-packages/socketio/namespace.py", line 282, in call_method
return method(*args)
File "/Library/Python/2.7/site-packages/flask_socketio/__init__.py", line 79, in recv_connect
self.socketio._dispatch_message(app, self, 'connect')
File "/Library/Python/2.7/site-packages/flask_socketio/__init__.py", line 137, in _dispatch_message
ret = self.messages[namespace.ns_name][message](*args)
File "/Library/Python/2.7/site-packages/flask_login.py", line 758, in decorated_view
return func(*args, **kwargs)
File "/Users/kramer65/repos/vg/app/views/webviews.py", line 418, in websocketConnect
join_room(g.user.id)
File "/Library/Python/2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: '_AppCtxGlobals' object has no attribute 'user'