如何在用户使用midd注销时删除用户

2024-07-06 18:19:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

Tags: thedjangoinfromimportidscacheuid
1条回答
网友
1楼 · 发布于 2024-07-06 18:19:53

您可以使用套接字,否则它不会真正显示online用户。你知道吗

如果没有插座,它将不会如此精确,但以下是您可以分步骤执行的操作:

  • 为用户创建最后一个活动(日期时间)字段。(以一种或任何方式存储此关系)

  • 在中间件中,更改代码以更新用户的最后一个活动字段。你知道吗

    if request.user.is_authenticated():
        user_activity, c = UserActivity.objects.get_or_create(user=request.user)
        user_activity.last_activity = timezone.now()
        user_activity.save()
    

这就是你所需要的。你知道吗

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

User.objects.filter(activities__last_activity__gte=timezone.now() - timedelta(seconds=30))

相关问题 更多 >