在django decorator中访问请求用户和url参数

时间:2017-05-14 22:03:53

标签: python django decorator python-decorators

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

@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

实现这一目标的最佳途径是什么?

1 个答案:

答案 0 :(得分:2)

你的装饰师应该是这样的

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, e:
            return HttpResponse('ERROR: User not present in the class')
        return old_fuction(request, class_id, *args, **kwargs)
    return new_function

如果UserClasses包含同时包含userclass_id的行(假设userunique),则会执行查看功能。否则将返回错误响应(错误:用户不在班级中)。

你应该查看函数

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

如果你想在视图函数中使用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, e:
            return HttpResponse('ERROR: User not present in the class')
        return old_fuction(request, class_id, class_, *args, **kwargs)
    return new_function

视图功能应该是

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

其中class_obj包含class_对象