python类装饰器

Django 类视图中的method_decorator 三种使用方法

首先导入 from django.utils.decorators import method_decorator

method_decorator 是将函数装饰器转换成方法装饰器。

方法一:

@method_decorator(check_login, name="get")
@method_decorator(check_login, name="post")
class HomeView(View):

    def get(self, request):
        return render(request, "home.html")

    def post(self, request):
        print("Home View POST method...")
        return redirect("/index/")

方法二:

class HomeView(View):

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

    def get(self, request):
        return render(request, "home.html")

    def post(self, request):
        print("Home View POST method...")
        return redirect("/index/")

方法三:

class HomeView(View):

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

    def get(self, request):
        return render(request, "home.html")
    
    @method_decorator(check_login)
    def post(self, request):
        print("Home View POST method...")
        return redirect("/index/")
原文地址:https://www.cnblogs.com/mqhpy/p/13902956.html