【发布时间】:2019-01-26 14:25:02
【问题描述】:
我正在考虑使用 django-notifications 和 Web Sockets 向 iOS/Android 和 Web 应用程序发送实时通知。所以我可能会使用 Django Channels。
我可以使用 Django Channels 来实时跟踪用户的在线状态吗?如果是,那么我如何在不不断轮询服务器的情况下实现这一点?
我正在寻找最佳做法,因为我找不到任何合适的解决方案。
更新:
到目前为止,我尝试过的是以下方法:
使用 Django Channels,我实现了一个 WebSocket 消费者,它在连接时会将用户状态设置为'online',而当套接字断开连接时,用户状态将设置为'offline'。
最初我想包含'away' 状态,但我的方法无法提供那种信息。
此外,当用户从多个设备使用应用程序时,我的实现将无法正常工作,因为连接可以在一个设备上关闭,但仍然在另一个设备上打开;即使用户有另一个打开的连接,状态也会设置为'offline'。
class MyConsumer(AsyncConsumer):
async def websocket_connect(self, event):
# Called when a new websocket connection is established
print("connected", event)
user = self.scope['user']
self.update_user_status(user, 'online')
async def websocket_receive(self, event):
# Called when a message is received from the websocket
# Method NOT used
print("received", event)
async def websocket_disconnect(self, event):
# Called when a websocket is disconnected
print("disconnected", event)
user = self.scope['user']
self.update_user_status(user, 'offline')
@database_sync_to_async
def update_user_status(self, user, status):
"""
Updates the user `status.
`status` can be one of the following status: 'online', 'offline' or 'away'
"""
return UserProfile.objects.filter(pk=user.pk).update(status=status)
注意:
我当前的工作解决方案是使用带有 API 端点的 Django REST 框架,让客户端应用程序发送具有当前状态的 HTTP POST 请求。
例如,Web应用程序跟踪鼠标事件并在online status oder x秒后,当没有更多的鼠标事件发布away status时,当标签/窗口即将关闭时,该应用程序会发送a状态为 offline 的 POST 请求。
这是一个可行的解决方案,具体取决于浏览器我在发送offline 状态时遇到问题,但它可以工作。
我正在寻找一种更好的解决方案,不需要不断地轮询服务器。
【问题讨论】:
标签: django django-channels django-notification