Django之CBV装饰器method_decorator

PS:CBV中添加装饰器

    def wrapper(func):

      def inner(*args,**kwargs):

        return func(*args,**kwargs)

      return inner

    #1.指定方法上添加装饰器

      class Foo(View):

        @method_decorator(wrapper)

        def get(self,request):

          pass

        def post(self,request):

          pass

    2.在类上添加

      @method_decorator(wrapper,name='dispatch')

      class Foo(View):

        def get(self,request):
          pass

        def post(self,request):

          pass

#CBV代码

复制代码
# 1.路由系统
urlpatterns = [
    url(r'^login.html$', views.Login.as_view()),
]

# 2.views类
"""
    get     查
    post    创建
    put     更新
    delete  删除
"""
# 根据request.method的方式自动执行对应的函数。
# 我们可以重写dispatch函数来实现类似装饰器的效果,dispatch内部根据反射来实现函数执行。
from django.views import View

class Login(View):
    def get(self,request):
        return render(request, "login.html")

    def post(self, request):
        name = request.POST.get("user")
        print(name)
        return HttpResponse("from post ")
    
    def dispatch(self, request, *args, **kwargs):
        print("-----before------")
        ret = super().dispatch(request,*args,**kwargs)
        print("-----after------")
        return ret

# # CBV应用装饰器
# django的bug,不能直接对类进行装饰,必须使用 method_decorator,把装饰器当作参数传进去。
from django.utils.decorators import method_decorator
@method_decorator(wrapper, name="post")
复制代码

你可能感兴趣的:(django)