如何为基于类的视图编写装饰器 - 基于视图中的对象的权限

时间:2012-04-04 13:24:06

标签: django django-class-based-views

现在我正在使用此应用进行权限检查:django-rules

然而,它已经超过一年没有更新,并且没有“新”(自django 1.3)基于类的视图的装饰器。我希望能够在urls.py上使用这样的:

url(r'^casos/(?P<pk>\d+)/editar/$', rules_permission_required('lawsuits.logical_check', raise_exception=True)(CaseUpdateView.as_view()), name='case_edit'),

我无法弄清楚如何从装饰器的基于类的视图中获取对象。你们有什么想法吗?这是我到目前为止所做的:

from django.utils.decorators import available_attrs
def rules_permission_required(perm, queryset=None, login_url=None, raise_exception=False):
    def wrapper(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def inner(request, *args, **kwargs):
            #view_func is the class based view -> <function MyEditView at 0x94e54c4>

            print view_func.get_object() # doesnt work
            print view_func(request, *args, **kwargs).get_object() # doesnt work either

            #any ideas?

            if not request.user.has_perm(perm, obj=obj):
                return redirect_to_login(request, login_url, raise_exception)
            return view_func(request, *args, **kwargs)
        return inner
    return wrapper

非常感谢提前!

2 个答案:

答案 0 :(得分:7)

在dispatch()方法上使用method_decoratorhttps://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-class-based-views

from django.utils.decorators import method_decorator
class ClassBasedView(View):
    @method_decorator(rules_permission_required)
    def dispatch(self, *args, **kwargs):
        return super(ClassBasedView, self).dispatch(*args, **kwargs)

或者您可以在您的url配置中设置as_view类方法的输出(如上面链接中所述),或者将实例保存到变量中。

class ClassBasedView(View):
    def dispatch(self, *args, **kwargs):
        return super(ClassBasedView, self).dispatch(*args, **kwargs)
class_based_view = rules_permission_required(ClassBasedView.as_view())

虽然我不太确定最后一个例子是否会导致线程安全问题(取决于Django如何处理实例)。最好的方法可能是坚持使用method_decorator

答案 1 :(得分:0)

我最终使用了类装饰器

def rules_permission_required(perm, queryset=None, login_url=None, raise_exception=False):

    def wrapper(cls):                
        def view_wrapper(view_func):
            @wraps(view_func, assigned=available_attrs(view_func))
            def inner(self, request, *args, **kwargs):
                # get object
                obj = get_object_from_classbased_instance(
                        self, queryset, request, *args, **kwargs
                    )

                # do anything you want
            return inner
        cls.dispatch = view_wrapper(cls.dispatch)
        return cls
    return wrapper