django中视图函数的FBV和CBV

1.什么是FBV和CBV

FBV是指视图函数以普通函数的形式;CBV是指视图函数以类的方式。

2.普通FBV形式

def index(request):
return HttpResponse('index')

3.CBV形式

3.1 CBV形式的路由

path(r'^login/',views.MyLogin.as_view())

3.2 CBV形式的视图函数

from django.views import View
class MyLogin(View):
def get(self,request): #get请求时执行的函数
	return render(request,'form.html')
def post(self,request): #post请求时执行的函数
	return HttpResponse('post方法')

FBV和CBV各有千秋
CBV特点是:
能够直接根据请求方式的不同直接匹配到对应的方法执行

4.CBV源码分析

核心在于路由层的views.MyLogin.as_view()--->其实调用了as_view()函数就等于调用了CBV里面的view()函数,因为as_view()函数是一个闭包函数,返回的是view---->view函数里面返回了dispatch函数--->dispatch函数会根据请求的方式调用对应的函数!

5.CBV添加装饰器的三种方式

from django.views import View #CBV需要引入的模块
from django.utils.decorators import method_decorator #加装饰器需要引入的模块
"""
CBV中django不建议你直接给类的方法加装饰器
无论该装饰器是否能都正常工作 都不建议直接加
"""
django给CBV提供了三种方法加装饰器
# @method_decorator(login_auth,name='get') # 方式2(可以添加多个针对不同的方法加不同的装饰器)
# @method_decorator(login_auth,name='post')
class MyLogin(View):
 @method_decorator(login_auth) # 方式3:它会直接作用于当前类里面的所有的方法
 def dispatch(self, request, *args, **kwargs):
 return super().dispatch(request,*args,**kwargs)
 # @method_decorator(login_auth) # 方式1:指名道姓,直接在方法上加login_auth为装饰器名称
 def get(self,request):
 return HttpResponse("get请求")
 def post(self,request):
 return HttpResponse('post请求')
作者:等日落原文地址:https://www.cnblogs.com/suncolor/p/16587022.html

%s 个评论

要回复文章请先登录注册