更新时间:2023-12-02 13:59:46
使用WebSockets绝对是更好的方法.
Using WebSockets is definitely the better approach.
您可以对连接数进行计数,而不必具有二进制的在线"/离线"状态:当连接新的WebSocket时,将在线"计数器加1,而当WebSocket断开连接时,将其减小.这样,当它为0
时,用户在所有设备上都处于脱机状态.
Instead of having a binary "online"/"offline" status, you could count connections: When a new WebSocket connects, increase the "online" counter by one, when a WebSocket disconnects, decrease it. So that, when it is 0
, then the user is offline on all devices.
类似这样的东西
@database_sync_to_async
def update_user_incr(self, user):
UserProfile.objects.filter(pk=user.pk).update(online=F('online') + 1)
@database_sync_to_async
def update_user_decr(self, user):
UserProfile.objects.filter(pk=user.pk).update(online=F('online') - 1)