Django Signal request_finished 获取用户实例

Django Signal request_finished get user instanse

我尝试理解 Django 中的信号。我正在为 DRF 创建项目。

from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in
from django.core.signals import request_finished

对于这个信号我可以抓住用户

@receiver(user_logged_in)
def last_user_login(sender, request, user, **kwargs):
    print('User **{}** logged in'.format(user))

而且我想抓住这个信号的用户,但据我所知这是不可能的。

@receiver(request_finished)
def last_user_request(sender, **kwargs):
    print('User made request')

我的目标:捕获最后一个用户请求并将此数据写入数据库。

有人可以帮助我吗?谢谢

request_finished 信号只有关于其发送者 class 的信息,正如您在 HttpResponseBase class 中看到的那样,它发送的位置:

signals.request_finished.send(sender=self._handler_class)

为了完成您想要的,您可以考虑编写一个 custom middleware,您可以在其中访问 request 对象,从而也可以访问 User。想清楚如果你真的想写到那里的数据库,它可能会很慢。

写一个custom middleware来实现:

middleware.py:

class SimpleMiddleware:
   def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.
    
    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
    
        response = self.get_response(request)
    
        <b>print(response.status_code)
        print(request.user.username)
        # Add user data in db....
        if request.method == 'POST':
            print(request.POST)</b>
    
        # Code to be executed for each request/response after
        # the view is called.
    
        return response

settings.py:

MIDDLEWARE = [

    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',    
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
     
    <b>'myproject.middleware.SimpleMiddleware',</b>
    
]