Django and drf source view resolution

0902 self-summary

Django and drf source view resolution

Analysis of a native Django CBV Source:. View

"""
1)as_view()是入口,得到view函数地址
2)请求来了调用view函数,内部调用dispatch函数完成请求分发
3)dispatch函数将请求方式映射成视图类的同名方法,完成请求的处理,得到相应
4)再将相应的结果一层层返回
"""

Two .drf CBV source code analysis: APIView

"""
1)as_view()是入口,得到view函数地址,在范围view函数地址时局部禁用csrf认证
2)请求来了调用view函数,内部调用(APIView类的)dispatch函数完成请求分发
3)dispatch函数 二次封装request、完成三大认证后,再将请求方式映射成视图类的同名方法,完成请求的处理,得到相应,再对相应做渲染处理
4)再将相应的结果一层层返回
"""

Dealt .APIView do

  • as_view: 就干了一件事,禁用csrf认证

  • dispatch:
    • 1) Secondary Packaging request
    • 2) Three certification

Four .drf local and global rendering rendering

We looked through the source code to render the content is JSONRendererstillBrowsableAPIRenderer

BrowsableAPIRenderer with the introduction JSONRenderer

from rest_framework.renderers import JSONRenderer from rest_framework.renderers import BrowsableAPIRenderer

  • Local Settings

    • In class we add the basis for the definition APIView of renderer_classes = [JSONRenderer]this page js data does not appear to render the display only

    E.g

    class UserAPIView(APIView):
      renderer_classes = [JSONRenderer]
    
        def get(self, request, *args, **kwargs):
            print(request.query_params)
            data = {
                'status': 0,
                'msg': 'get ok',
                'results': [],
                'token': '123.12321.231'
            }
            return Response(
                data=data,
                status=status.HTTP_200_OK,
                headers={'Token': '123as.masd21.asd213sd'},
                content_type='application/json'  # 默认就是application/json
            )
  • Global Settingssetting

    # drf配置
    REST_FRAMEWORK = {
        # 响应的渲染模块
        'DEFAULT_RENDERER_CLASSES': [
            'rest_framework.renderers.JSONRenderer',
            'rest_framework.renderers.BrowsableAPIRenderer',
        ],
        'DEFAULT_PARSER_CLASSES': [
            'rest_framework.parsers.JSONParser',  # 'application/json'
            'rest_framework.parsers.FormParser',  # 'application/x-www-form-urlencoded'
            'rest_framework.parsers.MultiPartParser'  # multipart/form-data
        ],
    }

Guess you like

Origin www.cnblogs.com/pythonywy/p/11448967.html