How to access request body when using Django Rest Framework and avoid getting RawPostDataException

前端 未结 2 1908
隐瞒了意图╮
隐瞒了意图╮ 2021-02-14 10:18

I need to get the raw content of POST request body (as a string) yet when I try to access request.body I\'m getting an exception:

django.http.request         


        
2条回答
  •  孤独总比滥情好
    2021-02-14 10:27

    I might be missing something here but I'm pretty sure you don't need to define a custom parser in this case...

    You can just use the JSONParser from DRF itself:

        from rest_framework.decorators import api_view
        from rest_framework.decorators import parser_classes
        from rest_framework.parsers import JSONParser
    
        @api_view(['POST']) 
        @parser_classes((JSONParser,)) 
        def example_view(request, format=None):
            """
            A view that can accept POST requests with JSON content.
            """
            return Response({'received data': request.data})
    

提交回复
热议问题