FBV和CBV

FBV -- function based view:

def home(request):
    print('home!!!')
    return render(request,'home.html')

CBV  -- class based view:

views.py
    from django.views import View
    class LoginView(View):
        # 通过请求方法找到自己写的视图类里面对应的方法
        def get(self,request):

            return render(request,'login2.html')
        def post(self,request):
            username = request.POST.get('uname')
            password = request.POST.get('pwd')
            print(username,password)

            return HttpResponse('登录成功!')
            
urls.py
    url(r'^login2/', views.LoginView.as_view()),

CBV通过不同的请求方法找到对应的试图类中的方法

关键点,反射

    def dispatch(self, request, *args, **kwargs):
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)  #反射

CBV的dispatch方法:

from django.views import View
class LoginView(View):
    # GET 
    def dispatch(self, request, *args, **kwargs):
        print('请求来啦')
        ret = super().dispatch(request, *args, **kwargs)
        print('到点了,走人了')
        return ret
    def get(self,request):
        print('get方法执行了')
        return render(request,'login2.html')
    def post(self,request):
        username = request.POST.get('uname')
        password = request.POST.get('pwd')
        print(username,password)
        return HttpResponse('登录成功!')

FBV加装饰器:

def n1(f):
    def n2(*args,**kwargs):
        print('请求之前')
        ret = f(*args,**kwargs)
        print('请求之后')
        return ret
    return n2
@n1
def home(request):
    print('home!!!')
    return render(request,'home.html')

CBV加装饰器:

from django.views import View
from django.utils.decorators import method_decorator

def n1(f):
    def n2(*args,**kwargs):
        print('请求之前')
        ret = f(*args,**kwargs)
        print('请求之后')
        return ret
    return n2

# @method_decorator(n1,name='get') #方式三
class LoginView(View):
    # GET
    # @method_decorator(n1)  #方式2 给所有方法加装饰器
    def dispatch(self, request, *args, **kwargs):
        # print('请求来啦')
        ret = super().dispatch(request, *args, **kwargs)
        # print('到点了,走人了')
        return ret

    # @method_decorator(n1)  #方式1
    def get(self,request):
        print('get方法执行了')
        return render(request,'login2.html')
    def post(self,request):
        username = request.POST.get('uname')
        password = request.POST.get('pwd')
        print(username,password)
        return HttpResponse('登录成功!')

 

posted @ 2021-03-11 18:19  笑而不语心自闲  阅读(77)  评论(0编辑  收藏  举报