django中视图函数的FBV和CBV

打印 上一主题 下一主题

主题 895|帖子 895|积分 2685

1.什么是FBV和CBV

FBV是指视图函数以普通函数的形式;CBV是指视图函数以类的方式。
2.普通FBV形式
  1. def index(request):
  2. return HttpResponse('index')
复制代码
3.CBV形式

3.1 CBV形式的路由
  1. path(r'^login/',views.MyLogin.as_view())
复制代码
3.2 CBV形式的视图函数
  1. from django.views import View
  2. class MyLogin(View):
  3. def get(self,request): #get请求时执行的函数
  4.         return render(request,'form.html')
  5. def post(self,request):  #post请求时执行的函数
  6.         return HttpResponse('post方法')
复制代码
FBV和CBV各有千秋
CBV特点是:
能够直接根据请求方式的不同直接匹配到对应的方法执行
4.CBV源码分析

核心在于路由层的views.MyLogin.as_view()--->其实调用了as_view()函数就等于调用了CBV里面的view()函数,因为as_view()函数是一个闭包函数,返回的是view---->view函数里面返回了dispatch函数--->dispatch函数会根据请求的方式调用对应的函数!
5.CBV添加装饰器的三种方式
  1. from django.views import View #CBV需要引入的模块
  2. from django.utils.decorators import method_decorator #加装饰器需要引入的模块
  3. """
  4. CBV中django不建议你直接给类的方法加装饰器
  5. 无论该装饰器是否能都正常工作 都不建议直接加
  6. """
  7. django给CBV提供了三种方法加装饰器
  8. # @method_decorator(login_auth,name='get')  # 方式2(可以添加多个针对不同的方法加不同的装饰器)
  9. # @method_decorator(login_auth,name='post')
  10. class MyLogin(View):
  11.     @method_decorator(login_auth)  # 方式3:它会直接作用于当前类里面的所有的方法
  12.     def dispatch(self, request, *args, **kwargs):
  13.         return super().dispatch(request,*args,**kwargs)
  14.     # @method_decorator(login_auth)  # 方式1:指名道姓,直接在方法上加login_auth为装饰器名称
  15.     def get(self,request):
  16.         return HttpResponse("get请求")
  17.     def post(self,request):
  18.         return HttpResponse('post请求')
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

不到断气不罢休

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表