开发者

Best Practices for implementing Chat in Django (storing online users)

I'm implementing a chat system in Django.

I'm having a bit of trouble deciding how to creat开发者_如何学Pythone the models which decide who are the online users. Two problems I see:

  1. you can't really tell when a user goes offline
  2. I want the "users" to be lightweight (no log-in necessary), which means I don't want to use Django's user system.

Any suggestions on how to go about modeling this?


Store this info in your cache. It's ephemeral enough that it doesn't belong in a long-term database, and access needs to be REALLY fast.

You don't need to store a lot of info to deal with a chat session, so storing it in the user's session (you can do this with anonymous non-logged in users, and then pull info from the "real" users table if they happen to be logged in) is the right way to go provided you're using the pure caching session backend and something like memcached.


I agree with Pail McMillan's answer that using a cache would be the right approach. In the past I have used Django's low level caching API which simply allows you to store key value pairs centrally.

I am not sure how efficient this would be but you could very simply store a comma separated string of the IDs of the users which are currently online:

from django.core.cache import cache

cache.set('users-online', '4,6,12,34')

and then:

for user_id in cache.get('users-online').split(','):
    user = User.objects.get(pk=user_id)
    # do something with the user ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜