Django FBV CBV 以及加装饰器

Django FBV CBV 以及加装饰器

FBV (funcation base views)

  视图里使用函数处理请求

  

re_path('books/(?P<year>\d{4})/(?P<month>\d{1,2})/', views.books),

 

def books(request,year='1000',month='12'):
    return HttpResponse('图书查看'+year+month)

CBV(class base views)

  视图里使用类处理请求(as_view 方法会返回一个同上的类似的view视图)

  

path('',views.books.as_view())

 

#cbv 模式
from django.views.generic import View
class books(View):
    # get 代表get 请求,如果为post 则为post 请求
    def get(self,request):
        return HttpResponse('图书查看GET')
    def post(self,request):
        return HttpResponse('图书查看post')

 

Dispatch 方法:

  通过重写父类的dispatch方法可以进行对于一次请求的处理进行拦截以及处理

    # 装饰器结构,dispath 是进行post get等请求进入方法,在寻找上下文自定义的方法时候进行反射的
    def dispatch(self, request, *args, **kwargs):
        print("请求来了")
        ret = super().dispatch(request,*args,**kwargs)
        print("请求走了")
        return ret

 

   在父类的dispatch方法中是这样的代码:

    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)

 

  通过getattr()进行对父类的同名的映射

装饰器-FBV:

在views视图里,可以写装饰器来进行对请求的处理,例如,当我们拥有一个这样的视图方法:

def base(request):
    return render(request,'app01/index.html')

 

装饰器如下:

def check(fun):
    def isLogIn(*args,**kwargs):
        print("请求前")
        ret = fun(*args,**kwargs)
        print("请求后")
        return ret
    return isLogIn

@check
def base(request):
    return render(request,'app01/index.html')

 

装饰器-CBV 

对于cbv使用装饰器,需要使用

from django.utils.decorators import method_decorator

对于CBV 单独的get 方法加装饰器方式:   @method_decorator(check)

 

check 为上面的check

# 第一种 -------------@method_decorator(check,name="get") 只加给get
class books(View):
    # get 代表get 请求,如果为post 则为post 请求
    # 第二种--------------@method_decorator(check) 只加给get
    def get(self,request):
        return HttpResponse('图书查看GET')
    def post(self,request):
        return HttpResponse('图书查看post')
    # dispath 是进行post get等请求进入方法,在寻找上下文自定义的方法时候进行反射的
    # 第三种--------------@method_decorator(check) 加给全部
    def dispatch(self, request, *args, **kwargs):
        print("请求来了")
        ret = super().dispatch(request,*args,**kwargs)
        print("请求走了")
        return ret

 

posted @ 2020-08-09 18:45  Sunny抹茶  阅读(153)  评论(0)    收藏  举报