码迷,mamicode.com
首页 > 其他好文 > 详细

CBV源码解析

时间:2018-09-17 17:51:57      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:对象   设计   nbsp   有一个   源码解析   返回   继承   http   举例   

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")

 

CBV源码解析

标签:对象   设计   nbsp   有一个   源码解析   返回   继承   http   举例   

原文地址:https://www.cnblogs.com/hnlmy/p/9662798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!