在Django中实现Chat的最佳实践(存储在线用户)
我正在 Django 中实现一个聊天系统。
我在决定如何创建决定谁是在线用户的模型时遇到了一些麻烦。我看到两个问题:
- 你无法真正判断用户何时离线。
- 我希望“用户”是轻量级的(无需登录),这意味着我不想使用 Django 的用户系统。
关于如何对此进行建模有什么建议吗?
I'm implementing a chat system in Django.
I'm having a bit of trouble deciding how to create the models which decide who are the online users. Two problems I see:
- you can't really tell when a user goes offline
- 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将此信息存储在您的缓存中。它是短暂的,不属于长期数据库,并且访问需要非常快。
您不需要存储大量信息来处理聊天会话,因此将其存储在用户会话中(您可以对匿名未登录用户执行此操作,然后从“真实”用户表中提取信息,如果如果您使用纯缓存会话后端和 memcached 之类的东西,那么(他们碰巧已登录)是正确的方法。
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.
我同意 Pail McMillan 的回答,即使用缓存是正确的方法。过去我使用过 Django 的低级缓存API 只是允许您集中存储键值对。
我不确定这有多高效,但您可以非常简单地存储当前在线用户的 ID 的逗号分隔字符串:
然后:
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:
and then: