drf 解析器简单使用

默认解析器

JSONParser, FormParser, MultiPartParser

view

class UserView(OrPermissionAPIView):
    from rest_framework.parsers import JSONParser, FormParser
    from rest_framework.negotiation import DefaultContentNegotiation
    parser_classes = [JSONParser, FormParser]
    content_negotiation_class = DefaultContentNegotiation

    def post(self, request, *args, **kwargs):
        # 获取url里的
        print(request.query_params, type(request.query_params))
        # 获取body里的
        print(request.data, type(request.data))
        return Response('post')

application/json

image

application/x-www-form-urlencoded

image

获取文件

class UserView(OrPermissionAPIView):
    from rest_framework.parsers import MultiPartParser
    from rest_framework.negotiation import DefaultContentNegotiation
    parser_classes = [MultiPartParser]
    content_negotiation_class = DefaultContentNegotiation

    def post(self, request, *args, **kwargs):
        file = request.data.get('data1')
        with open(file.name,mode='wb') as target:
            for chunk in file:
                target.write(chunk)

        return Response('post')

image

posted @ 2022-10-03 16:57  Sherwin_szw  阅读(21)  评论(0编辑  收藏  举报