一、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一样
class CBVTest(View):
def get(self,request):
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 == '':
return HttpResponse('登陆成功')
else:
return render(request,'test.html')
三、dispatch的使用
dispatch,相当于重写父类的用法,不加入dispatch则直接走父类的,写了则走自己写的类
class Test(View):
def dispatch(self,request,*args,**kwargs):
print('')
#或者加入对访问频率过多的IP进行限制过滤,对未登录的用户限制
obj = super().dispatch(request,*args,**kwargs)
print('')
#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 == '':
return HttpResponse('登陆成功')
else:
return render(request,'test.html')
结果:
111
333
222
CBVTest