Detailed analysis module Drf

The request module drf

  • The request is packaged drf request again on the basis of wdgi

  • wsgi the request as a request of the attribute drf: _request

  • The new request for the old request made fully compatible

  • The new request for more standardized data analysis: All parameters can be resolved to query_params splicing, all data packets are parsed into data in, and data belonging query_params QueryDict type, .dict () is converted into a native type dict

    Source code analysis

  • drf of APIView categories: Rewrite the as_view (), but the main logic still call the parent View of as_view (), a local disabled csrf certification focus: all the basic view class APIView inheritance drf view class, not doing csrf certified school test
  • The APIView drf class: override the dispatch (), on the secondary ruquest were encapsulated inside: self.initialize_request (request, * args, ** kwargs),

    实例:
        print(request)
        print(request._request.GET)
        print(request.META)
        print(request.META.get('HTTP_LLL'))
Inner core:
走drf的Request初始化方法__init__:self.request=request
drf的Request的getter方法__getattr__:先从self.request反射属性,没取到再冲drf的request中取

drf rendering module

  • Rendering property can be made by renderer_classes class matching of the data affect the view in the view class (partial match)

  • Drf can configure profiles of the project in view of the data DEFAULT_RENDERER_CLASSES response to the rendering done Configuration (Global)

  • If there is a view class in the global configuration, also a local configuration, priority go its own local configuration

    Source code analysis

  • Secondary treatment response object: dispatch method of APIView -> self.finalize_response (request, response, * args, ** kwargs)

  • Get render class object: into the finalize_response Method -> self.perform_content_negotiation (request, force = True)

  • Class object rendering obtained from the configuration file: perform_content_negotiation -> self.get_renderers () -> [renderer () for renderer in self.renderer_classes]

    局部:renderer_classes = [JSONRenderer,BrowsableAPIRenderer]
    
    全局:REST_FRAMEWORK = {
        # 渲染模块的全局配置:开发一般只配置json
        'DEFAULT_RENDERER_CLASSES': [
                    'rest_framework.renderers.JSONRenderer',]

drf parsing module

Service is targeted at packet data

  • Configuration can be done (partial configuration) the data packet is analyzed by the view parser_classes class attribute in the view class

  • It can be resolved by the configuration of the packet DEFAULT_PARSER_CLASSES configuration view in the configuration file drf project (Global)

    Source code analysis

  • APIView's dispatch method: self.initialize_request (request, * args, ** kwargs) is provided inside data analysis

  • self.get_parser_context (request) to parse the data provided, self.get_parsers () provides resolution class object (from the inside looking parsing class configuration)

    局部:parser_classes = [JSONParser, MultiPartParser, FormParser]
    
    全局: REST_FRAMEWORK ={'DEFAULT_PARSER_CLASSES': [
            'rest_framework.parsers.JSONParser',
            'rest_framework.parsers.FormParser',
            'rest_framework.parsers.MultiPartParser'
        ]}

drf exception module

Rewriting object abnormal abnormality information recording module (item on line)

  • EXCEPTION_HANDLER arranged in drf configuration settings, the function point custom exception_handler

  • drf abnormal, and will exception_handler callback function, carry the abnormal and unusual objects related content, complete information exception_handler different function returns the logging information and exception logs

    Source code analysis

  • In the dispatch APIView method, there is a large try ... except ..., exceptions to the code running abnormality processing module self.handle_exception (exc)

  • Mapping function from the configuration of the configuration process abnormality (abnormality custom point module is configured to customize their functions): self.get_exception_handler ()

  • Abnormal function exception_handler (exc, context) handle the exception, it will go its own: the first system to process (client side exception), the system did not handle (abnormal server), and then deal with their own

    Logging exception information needs to be recorded, so you need to customize, drf only deal with clients abnormal, the server to require manual processing, unified treatment results

    def exception_handler(exc, context):
        response = drf_exception_handler(exc, context)
    
        if response is None: # drf没有处理的异常(服务器异常)
            return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR, data={
                'status': 6,
                'exc': '%s' % exc
            })
    
        # 项目阶段,要记录到日志文件
        return Response(status=response.status_code, data={
            'status': 7,
            # drf处理的客户端异常,原始处理方式是将异常信息放在response对象的data中,data的格式是{'datail': '具体的异常信息'}
            'exc': '%s' % response.data.get('detail')
        })
    
    全局:REST_FRAMEWORK ={['EXCEPTION_HANDLER': 'api.utils.exception_handler']}

    # Drf response module

    • Response class object requires parameters generated, and the attributes of the object classes that can be used Response

    • Parameters: Response (data = data network status response code, status = response, header = response header information to carry a front end portion)

    • 属性:response.data response.status_code response.status_text

      The core and the source code

      源码:Response类的__init__方法
      核心:知道response对象产生可以传那些信息,response对象又是如何访问这些信息的

Guess you like

Origin www.cnblogs.com/lzss/p/11922442.html