django CBV模式源码执行过程

在说CBV模式之前,先看下FBV的url配置方式:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^xxx/', login),
    url(r'^index/', IndexView.as_view()),
]

FBV的方式,URl中视图函数是一个函数的名字,当访问这个url时才执行这个视图函数。那么猜想CBV也应该是如此,返回一个函数的句柄。

那一步步来看,IndexView.as_view() 是执行 IndexView类中的as_view()方法,IndexView类中没有改方法,那么往父类中找,在父类中找到as_view()方法。如下:

可以发现,在as_view()方法中,返回view。那么上面我们猜想的是正确的。

紧接着,请求来时,执行view方法,而在view方法中,返回了  return self.dispatch(request, *args, **kwargs)

那么,dispatch()中做了上面呢,看下源码:

    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()  或者post() 即请求方法的名+()。这样就去执行我们自己写的类中的get或者post方法了。

执行过程大概就是这样。

那么我们也可以重写dispatch(), 在里面加入需要做的事情。如下:

class IndexView(View):

    def dispatch(self, request, *args, **kwargs):
        # 执行父类的dispatch()
        method = super(IndexView, self).dispatch(request, *args, **kwargs)
        """
        在这里可以做一些事,比如所有请求都要执行的事情。然后再分发到对应的get或post或者其他方法上
        """
        return method

    def get(self, request):

        return HttpResponse('OK')

    def post(self, request):
        return HttpResponse('OK')

    def put(self, request):
        return HttpResponse('OK')

 



 

posted @ 2018-09-04 14:39  20180616  阅读(113)  评论(0编辑  收藏  举报