Location>code7788 >text

DRF-Parser parser component source code analysis and application

Popularity:890 ℃/2024-10-27 20:24:50

1. Parser source code analysis

Note: The following source code has been simplified for ease of understanding, and only the parser-related code has been retained.

# view function:
class MyView(APIView):
    def post(self, request):
        print() # trigger resolution process
        return Response("ok")
Parsing and getting data for source code analysis:

image
image

Get source code analysis of the parser:

image
image

Source code analysis of parser parsing data (using JSONParser as an example):

image

2. Practical application

# In the view class:
class MyView(APIView).
    # Specify the parser (if not specified then use the default parser_classes = [MultiPartParser, JSONParser, FormParser])
    parser_classes = [JSONParser, FormParser] # Only JSON and form data can be parsed.

    # Methods to match parsers (defaults to using methods in this class to match parsers, even if not explicitly written)
    content_negotiation_class = DefaultContentNegotiation

    def post(self, request).
        print()
        return Response("ok")