• CBV源码解析


    1、CBV(class based view)

    首先定义一个视图函数,用类的方式定义:

    举例:

    class LoginView(View):
    
            def get(self,request):
                return render(request,"login.html")

    url的设计:

    #url(r'^login/', views.LoginView.as_view()),

    可以直接点击as_view进入,但是我们正常走的话就是进入LoginView,继承了View,然后是执行类里边的as_view方法,as_view是个类方法,执行后肯定有一个返回值,这个返回值就是view,

    #url(r'^login/', View.view),

    然后是用户访问的时候执行的:

    一旦用户get访问login:

    走到view方法里边,执行self.dispatch,self就是我们自己定义的LoginView的实例对象。

    #login-----》view(request):
                         self = cls(**initkwargs)
                         return self.dispatch(request, *args, **kwargs):

    然后看这个类有没有dispatch方法,在我们自己定义的里边没有写,但是继承view里边有这个方法(源码里边的东西):

     def dispatch(self, request, *args, **kwargs):
            # Try to dispatch to the right method; if a method doesn't exist,
            # defer to the error handler. Also defer to the error handler if the
            # request method isn't on the approved list.
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed
            return handler(request, *args, **kwargs)

    简单来说就是:请求方式的分发,如果是get请求,执行get,是什么就执行什么:

    # 分发
                                        handler = getattr(self, request.method.lower())
                                        
                                        return handler(request, *args, **kwargs):
                                               def get(self,request):
                                                        return render(request,"login.html")
  • 相关阅读:
    sql server 的存储过程
    vue SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    数据结构 基本概念和术语
    vue v-show指令
    vue v-model :
    vue 指令
    vue 挂载点 实例 模板
    vue(1) 第一个例子
    【BZOJ1150】[CTSC2007]数据备份Backup 双向链表+堆(模拟费用流)
    【BZOJ1109】[POI2007]堆积木Klo 二维偏序
  • 原文地址:https://www.cnblogs.com/hnlmy/p/9662798.html
Copyright © 2020-2023  润新知