在Django中实现Chat的最佳实践(存储在线用户)

发布于 2024-10-02 12:00:24 字数 187 浏览 0 评论 0原文

我正在 Django 中实现一个聊天系统。

我在决定如何创建决定谁是在线用户的模型时遇到了一些麻烦。我看到两个问题:

  1. 你无法真正判断用户何时离线。
  2. 我希望“用户”是轻量级的(无需登录),这意味着我不想使用 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:

  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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心如荒岛 2024-10-09 12:00:24

将此信息存储在您的缓存中。它是短暂的,不属于长期数据库,并且访问需要非常快。

您不需要存储大量信息来处理聊天会话,因此将其存储在用户会话中(您可以对匿名未登录用户执行此操作,然后从“真实”用户表中提取信息,如果如果您使用纯缓存会话后端和 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.

帅的被狗咬 2024-10-09 12:00:24

我同意 Pail McMillan 的回答,即使用缓存是正确的方法。过去我使用过 Django 的低级缓存API 只是允许您集中存储键值对。

我不确定这有多高效,但您可以非常简单地存储当前在线用户的 ID 的逗号分隔字符串:

from django.core.cache import cache

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

然后:

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

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 ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文