gpt4 book ai didi

python - django装饰器中访问请求用户和url参数

转载 作者:行者123 更新时间:2023-12-01 02:59:21 25 4
gpt4 key购买 nike

我试图通过创建一个装饰器来处理总是重复的简单逻辑来消除冗余代码。基本上我创建的每个 View 都有以下逻辑来检查用户是否在类(class)中。

@login_required
def view(request, class_id):

class_ = UserClasses.objects.get(user=request.user, class_id=class_id)

# if the user is in the class
if class_:

我想执行以下操作:

查看:

@user_passes_test(in_class(request.user, class_id))
@login_required
def view(request, class_id):

装饰器:

from apps.classes.models import UserClasses

def in_class(request, class_id):
class_ = UserClasses.objects.get(user=request.user, class_id=class_id)
if class_:
return true
else:
return false

实现这一目标的最佳方法是什么?

最佳答案

你的装饰器应该是这样的

def user_passes_test(old_fuction):
def new_function(request, class_id, *args, **kwargs):
try:
class_ = UserClasses.objects.get(user=request.user, class_id=class_id)
except Exception as e:
return HttpResponse('ERROR: User not present in the class')
return old_fuction(request, class_id, *args, **kwargs)
return new_function

如果UserClasses包含同时具有userclass_id的行(假设user唯一的), View 函数将被执行。否则将返回错误响应(ERROR:用户不在类中)。

你查看的功能应该是

@user_passes_test
@login_required
def view(request, class_id):

如果您想要 View 函数中的class_对象,您可以通过简单的更改来完成。修改你的装饰器,例如

def user_passes_test(old_fuction):
def new_function(request, class_id, *args, **kwargs):
try:
class_ = UserClasses.objects.get(user=request.user, class_id=class_id)
except Exception as e:
return HttpResponse('ERROR: User not present in the class')
return old_fuction(request, class_id, class_, *args, **kwargs)
return new_function

View 函数应该是

@user_passes_test
@login_required
def view(request, class_id, class_obj):

其中 class_obj 包含 class_ 对象

关于python - django装饰器中访问请求用户和url参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43969236/

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