首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在用户使用中间件注销时将其删除

如何在用户使用中间件注销时将其删除
EN

Stack Overflow用户
提问于 2018-05-21 21:40:53
回答 1查看 74关注 0票数 0

我正在使用下面的中间件生成当前登录用户的列表。我遇到的问题是如何在用户注销后自动从online_nowonline_now_ids中删除用户。我已经尝试使用信号,但没有success...any的帮助,非常感谢

代码语言:javascript
复制
from django.core.cache import cache
from django.conf import settings
from django.contrib.auth.models import User
from django.utils.deprecation import MiddlewareMixin
from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_out
#Set Environment variables for settings.py

ONLINE_THRESHOLD = getattr(settings, 'ONLINE_THRESHOLD', 30*1)
ONLINE_MAX = getattr(settings, 'ONLINE_MAX', 50)
CACHE_MIDDLEWARE_SECONDS = getattr(settings, 'CACHE_MIDDLEWARE_SECONDS', 10)

def get_online_now(self):
    return User.objects.filter(id__in=self.online_now_ids or [])


class OnlineNowMiddleware(MiddlewareMixin):
    """
    Maintains a list of users who logged into the website.
    User ID's are available as `online_now_ids` on the request object,
    and their corresponding users are available lazzily as the `online_now`
    property on the request object
    """

    def process_request(self, request):
        #Get the index 
        uids = cache.get('online-now', [])

        #multiget on individual uid keys

        online_keys = ['online-%s' % (u,) for u in uids]
        fresh = cache.get_many(online_keys).keys()
        online_now_ids = [int(k.replace('online-','')) for k in fresh]

        #if user is authenticated add id to list
        if request.user.is_authenticated():
            uid = request.user.id
            #if uid in list bump to top
            # and remove earlier entry

            if uid in online_now_ids:
                online_now_ids.remove(uid)
            online_now_ids.append(uid)
            if len(online_now_ids) > ONLINE_MAX:
                del online_now_ids[0]


        #Attach modifications to the request object
        request.__class__.online_now_ids = online_now_ids
        request.__class__.online_now = property(get_online_now)

        #Set the new cache

        cache.set('online-%s' % (request.user.pk), True, ONLINE_THRESHOLD)
        cache.set('online-now', online_now_ids, ONLINE_THRESHOLD)
EN

回答 1

Stack Overflow用户

发布于 2018-05-21 22:48:22

您可以使用套接字来实现这一点,否则它不会真正向online用户显示。

如果没有套接字,它就不会那么准确,但以下是您可以在步骤中完成的操作:

  • 为用户创建最后一个活动(日期时间)字段。(无论您希望以何种方式存储此relationship)
  • In,请更改代码以更新用户的OneOnOne字段。

如果user_activity.save() ():request.user.is_authenticated():user_activity,c=user_activity user_activity.last_activity = timezone.now()

这就是你所需要的。

查询在线用户(不是精确查询,只是示例):

代码语言:javascript
复制
User.objects.filter(activities__last_activity__gte=timezone.now() - timedelta(seconds=30))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50450223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档