基于类的vi调度时login-required decorator的继承

2024-04-18 23:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多个视图都继承自基础视图。所有视图都需要login-required decorator。我想将它作为方法装饰器添加到基视图的分派中,然后不必将装饰器添加到每个子视图中。我没能做到这一点。在

这通常是不可能的吗?我错过了什么?我不知道什么?在

下面是我的代码的一个分解版本:

class CoreView(CoreMixin,TemplateView):
    pass


class BaseView(CoreView):

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(BaseView, self).dispatch(request, *args, **kwargs)


class MyView(BaseView):

    def dispatch(self, request, *args, **kwargs):
        "Do Stuff"

我试图做我的研究,但找不到答案。在

顺便说一句:我目前使用的是django1.8和python2.7。在


Tags: self视图requestdefrequiredargslogin装饰
3条回答

没有“直接”的方法,但是您可以在Python: Decorating a class method that is intended to be overwritten when inherited中找到一些解决方案。在

唯一适合您的方法是使用dispatch中的钩子,如:

class CoreView(CoreMixin,TemplateView):
    pass


class BaseView(CoreView):

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        do_dispatch(self, request, *args, **kwargs)
        return super(BaseView, self).dispatch(request, *args, **kwargs)

    def do_dispatch(self, request, *args, **kwargs):
        # This is the method we'll override
        pass         


class MyView(BaseView):

    def do_dispatch(self, request, *args, **kwargs):
        "Do Stuff"

试试看:

def login_required_class(decorator):
    def decorate(cls):
        for attr in cls.__dict__:
            if callable(getattr(cls, attr)):
                setattr(cls, attr, decorator(getattr(cls, attr)))
        return cls
    return decorate

@login_required_class(login_required)
class CoreView(CoreMixin,TemplateView):
    pass

@login_required_class(login_required)
class BaseView(CoreView):

    def dispatch(self, request, *args, **kwargs):
        return super(BaseView, self).dispatch(request, *args, **kwargs)

@login_required_class(login_required)
class MyView(BaseView):

    def dispatch(self, request, *args, **kwargs):
        "Do Stuff"

你的答案在文档中。对于基于类的视图,有mixins。如果您错过了permission required,也可以使用它。在

相关问题 更多 >