drf request module

A, drf use in accordance with

  1. Installation DRF :pip3 install djangorestframework

  2. Registration settings.py App :

    INSTALLED_APPS = [
        ...
        'rest_framework'
    ]
  3. Cbv completed based interface specifications meet restful

    # 视图层
    from rest_framework.views import APIView
    from rest_framework.response import Response
    # CBV接口
    class Test(APIView):
        def get(self,request,*args,**kwargs):
            print(request.GET)
            print(request.META)
    
            return Response({
                'status': 0,
                'msg': 'get ok'
            })
    
        def post(self,request,*args,**kwargs):
            print(request.POST)
    
            return Response({
                'status': 0,
                'msg': 'post ok',
            })
    # 路由层
    urlpatterns = [
        url(r'^api/', views.Test.as_view()),
    ]

Two, drf CBV source code analysis

  • First, the routing layer registration CBV , the method implemented by CBV as_view () , the same method and the CBV django implemented. But drf carried out some other process in the CBV. For example, although they are still the parent class to get the call as_view View , but the return of local disabled csrf certificationcsrf_exempt(view)
  • When the request came, routing view function mapping relationship will enter a request for distribution of the matching is successful dispatch()method.
  • In the dispatch()inner method in view of the implementation of the method prior to distribution to complete :
    • Second package Request : self.initialize_request (Request, * args, ** kwargs)
    • Three Certification : self.initial (request, * args, ** kwargs)
  • After the request has been handled view showing the method :
    • Unusual treatment : self.handle_exception (exc)
    • 二次封装response:self.finalize_response(request, response, *args, **kwargs)
'''rest_framework/views.py -> class APIView(view):中'''
    @classmethod
    def as_view(cls, **initkwargs):
        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
        # 调用父类as_view方法返回view对象
        view = super().as_view(**initkwargs)
        view.cls = cls
        view.initkwargs = initkwargs
        return csrf_exempt(view)
'''rest_framework/views.py -> class APIView(view):中'''
    def dispatch(self, request, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        # 二次封装request
        request = self.initialize_request(request, *args, **kwargs)
        self.request = request
        self.headers = self.default_response_headers  # deprecate?
        try:
            # 三大认证
            self.initial(request, *args, **kwargs)
            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)
        # 二次封装response
        self.response = self.finalize_response(request, response, *args, **kwargs)
        return self.response

Note: The next most about drf source will be starting from the dispatch method begins analysis

Third, the request module source code analysis

  • drf of APIView categories: Rewrite the as_view (), but the main logic still call the parent View of as_view (), local authentication is disabled csrf

    Key: All inherit a base view class APIView drf the view class, not doing csrf certified check

  • The APIView drf class: override the dispatch (), in the interior of the second package were request

    # 二次封装request
    request = self.initialize_request(request, *args, **kwargs)
  • initialize_request internal source analysis method

    • Examples of objects returned Request class.
    • Request class __init__method of the original requestplaced self._requestin
    • All splicing parameters are parsed into the query_params , all data packets are parsed into the data by @propertythe decorator to the method of packaging attribute data attribute.
    • query_params and data type belongs QueryDict can () into a native type dict by .dict
  • Internal Request class implements. Intercept method __getattr__to the value to be taken directly to the content of _request

# CBV接口
class Test(APIView):
    
    def get(self,request,*args,**kwargs):
        print(request._request.GET) # 直接找原来的request
        print(request.GET)  # 通过内部的getattr来找
        print(request.META) # 通过内部的getattr来找

        # QueryDict转化为原生dict
        print(request.query_params.dict())
        # 数据包数据
        print(request.data)

        return Response({
            'status': 0,
            'msg': 'get ok'
        })

    def post(self,request,*args,**kwargs):
        # 通过内部的getattr来找
        print(request.POST)

        # QueryDict转化为原生dict
        print(request.query_params.dict())
        print(request.data.dict())

        return Response({
            'status': 0,
            'msg': 'post ok',
        })

Guess you like

Origin www.cnblogs.com/XuChengNotes/p/11893206.html