• 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
                                               
  • 相关阅读:
    mem系函数总结
    shell----删除文件中的^M
    为tcp的connect设置超时时间
    ue-edit设置显示函数列表
    bep-10翻译
    mysql--慢查询,卡死等处理
    mongodb---js脚本操作速记
    佛主保佑,永无bug
    【php】中【event】之实现方式
    BI任务列表
  • 原文地址:https://www.cnblogs.com/hnlmy/p/9664502.html
Copyright © 2020-2023  润新知