[英]What is the best way to implement a 'last seen' function in a django web app?
I have a running django/apache2 + memcached app (ubuntu) and would like to keep track of logged in users that are online. 我有一个正在运行的django / apache2 + memcached应用程序(ubuntu),并希望跟踪登录的在线用户。
What would be the best way to track this? 追踪这个的最佳方法是什么?
I would prefer not writing to the database each time a logged in user loads a page; 每次登录用户加载页面时,我宁愿不写入数据库; but what other options are there?
但还有其他选择吗?
An approach might be: 一种方法可能是:
you create a middleware that does the following on process_response: 您创建了一个在process_response上执行以下操作的中间件:
now you have all currently logged in users in your auth.User table. 现在,您已在auth.User表中拥有所有当前登录的用户。 All Users that have a last_login newer than datetime.now()-interval(15minutes) might be considered "online".
last_login比datetime.now() - interval(15分钟)更新的所有用户可能被视为“在线”。
The database will be written for every logged in user about every 10 minutes. 将每隔10分钟为每个登录用户编写数据库。 Adjust the values "10" and "15" to your needs.
根据需要调整值“10”和“15”。
The advantage here is that database writes are rare (according to your two numeric settings 10/15). 这里的优点是数据库写入很少(根据您的两个数字设置10/15)。 And for speed optimization make sure that last_login is indexed, so a filter on this field including Count is really fast.
对于速度优化,请确保将last_login编入索引,因此包含Count的此字段的过滤器非常快。
Hope this helps. 希望这可以帮助。
内存中的散列映射或队列,每小时左右运行一个任务以保留它。
You need to persist the info server-side, integrity isn't critical, throughput and latency are important. 您需要保持信息服务器端,完整性并不重要,吞吐量和延迟很重要。 That means you should use some sort of key-value store.
这意味着你应该使用某种键值存储。
Memcached and redis have keys that expire. Memcached和redis的密钥已过期。 You probably have memcached already installed, so use that.
你可能已经安装了memcached,所以使用它。
You can reset expiry time of the user:last-seen:$username
key every visit, or you can use mawimawi's cookie technique and have expiry = 4 * cookie-lifetime. 您可以重置
user:last-seen:$username
到期时间user:last-seen:$username
每次访问都需要user:last-seen:$username
键,或者您可以使用mawimawi的cookie技术并且有expiry = 4 * cookie-lifetime。
You can't do that in django without using a database/persistent-storage because of the same reason why django sessions are stored in database: There can be multiple instances of your applications running and the must synchronize their states+data through a single persistence source [1] 你不能在不使用数据库/持久存储的情况下在django中这样做,因为django会话存储在数据库中的原因相同:你的应用程序可能有多个实例在运行,必须通过一个持久性同步它们的状态+数据来源[1]
Alternatively, you might want to write this information in a folder in a file named with user id and then check its create/modified date to find the required information. 或者,您可能希望将此信息写入以用户标识命名的文件中的文件夹中,然后检查其创建/修改日期以查找所需信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.