• 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请求')
    
  • 相关阅读:
    9月19日学习记录
    安科瑞高等学校校园建筑节能监管系统建设
    关于割接9000W数据的一些事
    一云多芯 | 云轴科技ZStack助力张家口建设信创资源池
    【LeetCode题目详解】第十章 单调栈part02 ● 503.下一个更大元素II ● 42. 接雨水 (day59补)
    Unity随笔:C#运行时
    单正态总体和双正态总体的假设检验
    关于butterfly主题
    用Python订正数据
    2022-09-02 mysql/stonedb-读取Pack数据流程记录
  • 原文地址:https://www.cnblogs.com/suncolor/p/16587022.html