zoukankan      html  css  js  c++  java
  • APIView源码解析

    1、首先安装pip install djangorestframework

    2、导入from rest_framework.views import APIView

    class Courses(APIView):
        def get(self, request):
            course_list = Course.objects.all()
            ret = []
            for course in course_list:
                ret.append({
                    "title": course.title,
                    "desc": course.desc
                })
            return HttpResponse(json.dumps(ret, ensure_ascii=False))
    
        def post(self, request):
            print(request.data)
            return HttpResponse("ok")

    3、url的设计:

     url(r'^courses/', views.Courses.as_view()),

    4、首先进入的是Courses类里边的APIView,点进去执行as_view()方法。源码如下:

        def as_view(cls, **initkwargs):
            """
            Store the original class on the view function.
    
            This allows us to discover information about the view when we do URL
            reverse lookups.  Used for breadcrumb generation.
            """
            if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
                def force_evaluation():
                    raise RuntimeError(
                        'Do not evaluate the `.queryset` attribute directly, '
                        'as the result will be cached and reused between requests. '
                        'Use `.all()` or call `.get_queryset()` instead.'
                    )
                cls.queryset._fetch_all = force_evaluation
    
            view = super(APIView, cls).as_view(**initkwargs)
            view.cls = cls
            view.initkwargs = initkwargs
    
            # Note: session based authentication is explicitly CSRF validated,
            # all other authentication is CSRF exempt.
            return csrf_exempt(view)

    然后执行的是父类里边的as_view方法,返回的就是父类里边的view方法。

    简单来说就是:

    # url(r'^courses/', APIView.as_view()),
          # url(r'^courses/', View.view),

    5、用户一旦访问,开始执行:

    执行父类的view,

    view(reqeust):
                                  self = cls(**initkwargs) 
                                  return self.dispatch(request, *args, **kwargs) #      APIView.dispatch()  
                                         def dispatch(request, *args, **kwargs):

    然后执行的就是dispatch,在我们的类里边找dispatch,找不到往APIView里边找,源码是:

        def dispatch(self, request, *args, **kwargs):
            """
            `.dispatch()` is pretty much the same as Django's regular dispatch,
            but with extra hooks for startup, finalize, and exception handling.
            """
            self.args = args
            self.kwargs = kwargs
            request = self.initialize_request(request, *args, **kwargs)
            self.request = request
            self.headers = self.default_response_headers  # deprecate?
    
            try:
                self.initial(request, *args, **kwargs)
    
                # Get the appropriate handler method
                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
    
                response = handler(request, *args, **kwargs)
    
            except Exception as exc:
                response = self.handle_exception(exc)
    
            self.response = self.finalize_response(request, response, *args, **kwargs)
            return self.response

    简单来说:

     def dispatch(request, *args, **kwargs):
                                         
                                            # 1 重装一个新的request对象
                                            
                                            # 2 认证组件,权限组件,频率组件                                     
                                         
                                            handler = getattr(self, request.method.lower())
                                            response = handler(request, *args, **kwargs)        
                                            return response
                                               
  • 相关阅读:
    各种协议与HTTP协议之间的关系
    在浏览器中输入url地址到显示主页的过程
    TCP 协议如何保证可靠传输
    TCP,UDP 协议的区别
    TCP 三次握手和四次挥手
    OSI与TCP/IP各层的结构与功能,用到的协议
    424. 替换后的最长重复字符
    webstorm快捷键
    S1:动态方法调用:call & apply
    S1:原型继承
  • 原文地址:https://www.cnblogs.com/hnlmy/p/9664502.html
Copyright © 2011-2022 走看看