gpt4 book ai didi

Django Signals request_finished 获取用户实例

转载 作者:行者123 更新时间:2023-12-04 07:57:20 25 4
gpt4 key购买 nike

我试图理解 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')
我的目标:捕获最后一个用户请求并将此数据写入数据库。
有人可以帮助我吗?谢谢。

最佳答案

写个 custom 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)

print(response.status_code)
print(request.user.username)
# Add user data in db....
if request.method == 'POST':
print(request.POST)


# Code to be executed for each request/response after
# the view is called.

return response

设置.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',

'myproject.middleware.SimpleMiddleware',

]

关于Django Signals request_finished 获取用户实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66637729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com