as_view() 源码解析

 @classonlymethod
    def as_view(cls, **initkwargs):   
        """Main entry point for a request-response process."""
        for key in initkwargs:
            if key in cls.http_method_names:
                raise TypeError("You tried to pass in the %s method name as a "
                                "keyword argument to %s(). Don't do that."
                                % (key, cls.__name__))
            if not hasattr(cls, key):
                raise TypeError("%s() received an invalid keyword %r. as_view "
                                "only accepts arguments that are already "
                                "attributes of the class." % (cls.__name__, key))

        def view(request, *args, **kwargs):    #只是定义了一下并没有执行
      # cls LoginView的实例对象 self
= cls(**initkwargs) if hasattr(self, 'get') and not hasattr(self, 'head'): self.head = self.get self.request = request self.args = args self.kwargs = kwargs
       #分发
return self.dispatch(request, *args, **kwargs) view.view_class = cls view.view_initkwargs = initkwargs # take name and docstring from class update_wrapper(view, cls, updated=()) # and possible attributes set by decorators # like csrf_exempt from dispatch update_wrapper(view, cls.dispatch, assigned=()) return view #返回一个函数对象

 

 

 

 view函数并没有执行

 

 

用户  get请求访问Login

path('/login/,'执行view(request))

 

 

#self  调的distouch  但是LOginVIew没有dispatch  ,去父类里去找

#反射  getattr

     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.
      #
# http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

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)

 

 

 

from django.views import View

class LoginView(View):
  # 如果自己定义 dispatch 一定要return 返回值
    def dispatch(self, request, *args, **kwargs):
        print("dispatch.....")
        ret=super().dispatch(request, *args, **kwargs)
        return ret


    def get(self,request):
        print("GET....")
        return render(request,"login.html")

    def post(self,request):
        print("post.....")
        return HttpResponse("OK")

    def delete(self,request):
        pass

    def put(self,request):
        pass

 

posted @ 2018-11-07 19:15  2275114213  阅读(501)  评论(0)    收藏  举报