一、FBV

  function base views 平常我们的写法,一个URL对应一个视图函数

二、CBV

  1、url 配置

 path('test/',views.CBVTest.as_views())

     2、from  django.views import View

    前台发过来的get请求,就会相应get方法,post就会相应post方法,get方法和post方法里面跟FBV一样

 1 class CBVTest(View):
 2     def get(self,request):
 3         print(request.method)
 4         return render(request,'test.html')
 5     def post(self,request):
 6         name = request.get('name')
 7         print(name)
 8         pwd = request.get('pwd')
 9         if name == 'wudi' and pwd == '123':
10             return HttpResponse('登陆成功')
11         else:
12             return render(request,'test.html')

 

三、dispatch的使用

  dispatch,相当于重写父类的用法,不加入dispatch则直接走父类的,写了则走自己写的类

class Test(View):
    def dispatch(self,request,*args,**kwargs):
        print('111')
        #或者加入对访问频率过多的IP进行限制过滤,对未登录的用户限制
        obj = super().dispatch(request,*args,**kwargs)
        print('222')
        #obj.set_cookie
        return obj

    def get(self,request):
    print('333') print(request.method)
return render(request,'test.html') def post(self,request): name = request.get('name') print(name) pwd = request.get('pwd') if name == 'wudi' and pwd == '123': return HttpResponse('登陆成功') else: return render(request,'test.html')

结果:

  111

  333

  222

    

CBVTest